Review of development issues of the week (August 7, 2023-August 13, 2023)

1. The difference between Arrays.asList() and new ArrayList()

1.1 Arrays

Arrays.asList()and Arrays source code
Insert image description here
Insert image description here

ArraysIt is java.utila class under the package

Below is Arrays.asList()the source code.

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray. The returned list is serializable and implements RandomAccess.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
           List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
       
Params:
a – the array by which the list will be backed
Type parameters:
<T> – the class of the objects in the array
Returns:
a list view of the specified array
@SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
    
    
        return new ArrayList<>(a);
    }

Arrays.asListMethod, using this method will create a fixed-size List object for the array. This method just wraps the array so that the List can be used in the program. No data is copied or created in this wrapper.
At the same time, we cannot modify the length of the newly created List, because adding or deleting elements in the List is not allowed.
However, we can modify the elements in the array in the newly created List. It should be noted that if you modify the element data in the List, the corresponding data in the Array will also be modified.
Insert image description here

Replenish:

Refer to https://blog.csdn.net/weixin_45404202/article/details/120518876
https://cloud.tencent.com/developer/article/1860630
Arrays.asList(strs) removeAll causes java.lang.UnsupportedOperationException exception


Insert image description here

1.1.1 Supplement ArrayList(Arrays.asList(array))

Like the Arrays.asList method, we can also use ArrayList<>(Arrays.asList(array)) to create a List from an Array.

However, what is different from the above method is that the List created using this method is copied from the data in the old Array. This new List has nothing to do with the old Array, and the operations on the data in the new List will not be affected. to the data in the old Array.

In other words, the List created using this method can add and delete elements in the List.
Insert image description here

Supplement 2:

List<String> timeList = Arrays.asList();
System.out.println(timeList);	
List<String> list = new ArrayList<>();
System.out.println(timeList.equals(list));


[]
true

Process finished with exit code 0

1.2 ArrayList()

The difference between Arrays.asList() and new ArrayList() (detailed explanation)

package java.util;
public class Arrays {
    
    
     /**
     * Returns a fixed-size list backed by the specified array.  (Changes to
     * the returned list "write through" to the array.)  This method acts
     * as bridge between array-based and collection-based APIs, in
     * combination with {@link Collection#toArray}.  The returned list is
     * serializable and implements {@link RandomAccess}.
     *
     * <p>This method also provides a convenient way to create a fixed-size
     * list initialized to contain several elements:
     * <pre>
     *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
     * </pre>
     *
     * @param <T> the class of the objects in the array
     * @param a the array by which the list will be backed
     * @return a list view of the specified array
     */
    @SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
    
    
        return new ArrayList<>(a);
    }
    
    /**
     * @serial include
     */
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
    
    
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;

        ArrayList(E[] array) {
    
    
            a = Objects.requireNonNull(array);
        }

        @Override
        public int size() {
    
    
            return a.length;
        }

        @Override
        public Object[] toArray() {
    
    
            return a.clone();
        }
        .......
    }
}
  1. Arrays is a class in the java.util package. By calling the asList() method, a collection is obtained. The implementation of the asList() method is new ArrayList();. But it is worth noting that the ArrayList of new is not the ArrayList in the java.util package, but the internal class ArrayList in Arrays.

  2. Although the internal class java.util.Arrays.ArrayList also inherits the abstract class AbstractList, it does not implement methods such as add() like java.util.ArrayList. In this case, if the add() method is called, in fact Just call the add() method in the parent class AbstractList class, but AbstractList.add() throws an exception.

  3. In addition, the collection obtained by Arrays.asList() is a reference to the original array. When initializing java.util.Arrays.ArrayList, the original data is stored in a private and final array.

AbstractList source code:

/**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E set(int index, E element) {
    
    
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public void add(int index, E element) {
    
    
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E remove(int index) {
    
    
        throw new UnsupportedOperationException();
    }
public class Test {
    
    
    public static void main(String[] args) {
    
    
    
        String[] stringArray = new String[]{
    
    "A", "B", "C", "D"};
        List<String> stringList = Arrays.asList(stringArray);

        stringList.set(0,"E");

        Arrays.stream(stringArray).forEach((e)-> System.out.println(e));
        System.out.println("--------------");
        stringList.stream().forEach((e)-> System.out.println(e));
       System.out.println("--------------");
        stringList.add("F");
    }
}

Insert image description here

  • The ArrayList returned by Arrays.asList is a fixed-size List object. It only wraps the Array and returns a reference to the Array (a = Objects.requireNonNull(array);). If the list modifies the elements, then Also changes the value of Array.
  • Methods such as add and remove are not implemented (this operation is not supported, and an exception java.lang.UnsupportedOperationException will be thrown after the operation).

new ArrayList()
List<String> list = new ArrayList();

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    
    
 /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
    
    
        if (initialCapacity > 0) {
    
    
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
    
    
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
    
    
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
    
    
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
    
    
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
    
    
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
    
    
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
}
  • ArrayList is a class in the java.util package. As shown in the above code, ArrayList inherits the abstract class AbstractList and implements the List interface.
  • The List interface is a relatively important interface for collections. Here are the basic operation methods of collections, such as add, remove and a series of operations. Although the abstract class AbstractList implements the List interface and also implements add, remove and other methods, it only throws UnsupportedOperationException(). The specific implementation still depends on the ArrayList class.

1.2.1 Several methods of creating ArrayList

1. 使用默认构造函数:
```java
ArrayList<String> list = new ArrayList<>();
  1. Constructor to specify initial capacity:
ArrayList<String> list = new ArrayList<>(10);
  1. Convert an array to an ArrayList using the Arrays.asList() method:
String[] array = {
    
    "apple", "banana", "orange"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
  1. Add elements to the ArrayList using the Collections.addAll() method:
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "apple", "banana", "orange");
  1. Use Double Brace Initialization:
ArrayList<String> list = new ArrayList<>() {
    
    {
    
    
    add("apple");
    add("banana");
    add("orange");
}};

2. How to use group by in Mysql

Insert image description here

Why does SELECT * FROM tableName GROUP BY columnName report a syntax error?

group by multiple times

SELECT count(*), sum(price) 
FROM (
	SELECT dining_date, card_no, dining_type, dining_hall_id, price 
	FROM dining_logs
	WHERE staff_type=3 AND dining_date BETWEEN 20230101 AND 20230131 AND dining_hall_id <> 7
	GROUP BY dining_date, card_no, dining_type, dining_hall_id
) t

3.Draw a picture

The design of the project takes time to draw various drawings. This is just supplementary information https://plantuml.com/zh/

4. Time reversal

.sorted(Comparator.comparing(MoConfigDetailVo::getOpUpdatedAt).reversed())
				.collect(Collectors.toList());

5. Factory + strategy design pattern

First define a strategy pattern interface

public interface Strategy {
    
    
	void process(T t, U u, V v);
}

Then create the implementation class of the interface, that is, different classes for each strategy implementation in different situations. There must be multiple implementation classes.

public class TStrategy implements Strategy {
    
    
	@Override
	public void process(T t, U u, V v) {
    
    
		实现业务逻辑
	}
}

Finally build a factory class

public class Factory {
    
    
	private static final Map<T, Strategy> STRATEGY_MAP;

	static {
    
    
		STRATEGY_MAP = new HashMap<>();
		STRATEGY_MAP.put(t, new TStrategy());
		STRATEGY_MAP.put(t, new SStrategy());
		STRATEGY_MAP.put(t, new UStrategy());
		STRATEGY_MAP.put(t, new VStrategy());
		STRATEGY_MAP.put(t, new WStrategy());
	}

	public static Strategy createStrategy(T t) {
    
    
		return STRATEGY_MAP.get(t);
	}
}

In the actual business code

实现类如TStrategy strategy = Factory.createStrategy(t);
	if (strategy != null) {
    
    
	strategy.process(t, u, v);
	}

6.List annotation @Value

/**
 * id集合
 */
@Value("${id:11,1011,22,92,120}")
private List<Integer> ids;

7. Add fields to a table

ALTER TABLE  a  ADD COLUMN `b_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'B区id' AFTER `time`;

8.Loading order of Java classes

https://www.cnblogs.com/sxkgeek/p/9647992.html

9. Another strategy + factory

factory

@Component
public class Factory {
    
    
	private static final Map<Integer,Class< ? extends Strategy>> STRATEGY_MAP = new HashMap<>(4);

	@PostConstruct
	public void init() {
    
    
		STRATEGY_MAP.put(Integer code, Atrategy.class);
		STRATEGY_MAP.put(Integer code, BStrategy.class);
		STRATEGY_MAP.put(Integer code, CStrategy.class);
		STRATEGY_MAP.put(Integer code, DStrategy.class);
	}

	public static Class< ? extends Strategy> createStrategy(Integer code) {
    
    
		return STRATEGY_MAP.get(code);
	}
}
public interface Strategy {
    
    
	void process(Entity record, Integer i, Vo res);
}

One of the classes that implements Strategy needs to be injected into container management because it @Autowiredis . For example, I only write an implementation of Strategy.daospring

@Service
public class BStrategy implements Strategy {
    
    
	@Autowired
	private MoDao moDao;

	@Resource
	private Client hrClient;

	@Override
	public void process(MoEntity moRecord, Integer userGroup, MoDetailVo res) {
    
    
		LambdaQueryWrapper<Entity> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Entity::getMoListId, moRecord.getId());
		queryWrapper.eq(Entity::getUserGroup, userGroup);
		queryWrapper.eq(Entity::getDiningDay, moRecord.getDiningDay());
		queryWrapper.eq(Entity::getMoTypeId, moRecord.getMoTypeId());
		queryWrapper.eq(Entity::getDiningShift, moRecord.getDiningShift());
		List<MoPeopleListEntity> records = moPeopleListDao.list(queryWrapper);

		if (records.isEmpty()) {
    
    
			return;
		}

	
		List<String> Ids = records.stream()
				.map(Entity::getUserId)
				.collect(Collectors.toList());

		
		Map<String, StaffInfo> staffMap = hrClient.fetchStaffByFeishuIds(Ids).stream()
				.collect(Collectors.toMap(StaffInfo::getId, e -> e));

		// 略...

		res.getPeople().getBlueCollar().addAll(peopleDetailList);
	}
}

In the business code, the function is implemented by getting the object SpringBeanUtil.getBean()from springthe container

Class<? extends Strategy> strategyClass = Factory.createStrategy(item.getCode());
			Strategy strategy = SpringBeanUtil.getBean(strategyClass);
			if (strategy != null) {
    
    
				strategy.process(moListRecord, item.getCode(), res);
			}
public class SpringBeanUtil implements ApplicationListener<ApplicationStartedEvent> {
    
    
    private static ApplicationContext applicationContext;

    public SpringBeanUtil() {
    
    
    }

    public static ApplicationContext getApplicationContext() {
    
    
        return applicationContext;
    }

    public static Object getBean(String name) {
    
    
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
    
    
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
    
    
        return getApplicationContext().getBean(name, clazz);
    }

    public String getActiveProfile() {
    
    
        return applicationContext.getEnvironment().getActiveProfiles()[0];
    }

    public void onApplicationEvent(ApplicationStartedEvent event) {
    
    
        synchronized(this) {
    
    
            if (applicationContext == null) {
    
    
                applicationContext = event.getApplicationContext();
            }

        }
    }
}

10. @PostConstruct

@PostConstructis a commonly used annotation in Java, which is used to specify a method to be executed immediately after the object is created. This annotation is typically used to initialize resources, perform configuration, or perform other one-time operations.

Annotated @PostConstructmethods will be called after dependency injection is complete, but before the object is put into the service. It can be used in any class or bean, including ordinary POJO classes, Spring-managed components, EJBs, etc.

Here is an example showing how to use @PostConstructannotations in a Spring component:

@Component
public class MyComponent {
    
    

    @PostConstruct
    public void init() {
    
    
        // 在对象创建后进行初始化操作
        System.out.println("执行初始化操作");
    }
}

In the above code, MyComponentthe class is annotated as a Spring component and annotations init()are used on the methods @PostConstruct. When the Spring container creates and initializes MyComponentthe object, init()the method will be called automatically.

It should be noted that @PostConstructannotations need to rely on Spring or other frameworks to ensure correct calling of methods. In a pure Java environment, @PostConstructannotations may not be recognized and triggered.

Guess you like

Origin blog.csdn.net/Blue_Pepsi_Cola/article/details/132262049