[Work Record] Rewrite equals() to solve the problem of List's indexOf() failure

      When I was looking at the company code a few days ago, my colleague wrote a method to reverse the List from the middle. It was very interesting. I wrote one myself. The List contains a Form. The basic code is as follows:

package exec;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
//Main program class - vincent
public class ChangeSequence {

	public static void main(String[] args) {
		List<OrderForm> orderList = new LinkedList<OrderForm>();
		orderList = getOrderInfo();
		orderList = sequenceChange(orderList, 3);
	}

	public static List<OrderForm> sequenceChange(List<OrderForm> params, Integer orderId){
		if(null == orderId){
			return new LinkedList<>(params);
		}
		
		OrderForm form = new OrderForm();
		
		form.setId(params.get(3).getId());
		int index = params.indexOf(form);
		
		// whether the full length
		if(index < params.size()){
			List<OrderForm> formList = new LinkedList<OrderForm>();
			formList.addAll(params.subList(index, params.size()));
			formList.addAll(params.subList(0, index));
			
			for(OrderForm form1 : formList){
				System.out.println("Order after sorting" + form1.getId());
			}
			
			return formList;
		}
		return new LinkedList<>(params);
	}
	
	public static List<OrderForm> getOrderInfo(){
		List<OrderForm> orderList = new LinkedList<OrderForm>();
		for(int i=0;i<10;i++){
			OrderForm form = new OrderForm();
			form.setId((long)i);
			form.setName("员工" + i);
			Random random = new Random(100);
			form.setScore(random);
			if(i % 3 == 0){
				form.setGroup("A");
			}else if(i % 3 == 1){
				form.setGroup("B");
			}else{
				form.setGroup("C");
			}
			orderList.add(form);
		}
		
		for(OrderForm form1 : orderList){
			System.out.println("Order before sorting" + form1.getId());
		}
		
		return orderList;
	}
}
package exec;

import java.util.Random;
//form entity class
public class OrderForm {
	
	private Long id;
	private String name;
	private Random score;
	private String group;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Random getScore() {
		return score;
	}
	public void setScore(Random random) {
		this.score = random;
	}
	public String getGroup() {
		return group;
	}
	public void setGroup(String group) {
		this.group = group;
	}
}

     Problem found during operation:

form.setId(params.get(3).getId());
int index = params.indexOf(form);

      As above, this code only assigns the id through the form, and then matches it in the List<Form>. The index is "-1" every time. It is found that when the content in the List is Object, it must be matched through indexOf() to find the form. Each attribute value of the must match.

      Then I changed my mind:

private List<BwAutoLoanEmpDailyForm> turnRoundEmpList(List<BwAutoLoanEmpDailyForm> orginEmpList, Long empId) {
	List<Long> empIds = new ArrayList<Long>();
	for (BwAutoLoanEmpDailyForm form: orginEmpList) {
		empIds.add(form.getDailyEmpId());
	}
	int index = empIds.indexOf(empIds) + 1;
}
      The above problem can be solved by picking out the ids of all Objects in the List, forming a new List, and then finding the position of the index.

      However, this approach is not good enough. The complexity of the two dimensions of "idle" and "time" has all increased. Under the guidance of colleagues, I looked at the source code of this indexOf(), as follows:

      1. The indexOf() method in List.java

public interface List<E> extends Collection<E> {
	/**
	 * Returns the index of the first occurrence of the specified element
	 * in this list, or -1 if this list does not contain the element.
	 * More formally, returns the lowest index <tt>i</tt> such that
	 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
	 * or -1 if there is no such index.
	 *
	 * @param o element to search for
	 * @return the index of the first occurrence of the specified element in
	 *         this list, or -1 if this list does not contain the element
	 * @throws ClassCastException if the type of the specified element
	 *         is incompatible with this list
	 *         (<a href="Collection.html#optional-restrictions">optional</a>)
	 * @throws NullPointerException if the specified element is null and this
	 *         list does not permit null elements
	 *         (<a href="Collection.html#optional-restrictions">optional</a>)
	 */
    int indexOf(Object o);

}

     2. indexOf() in ArrayList

/**
 * Returns the index of the first occurrence of the specified element
 * in this list, or -1 if this list does not contain the element.
 * More formally, returns the lowest index <tt>i</tt> such that
 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
 * or -1 if there is no such index.
 */
public int indexOf(Object o) {
	if (o == null) {
		for (int i = 0; i < size; i++)
			if (elementData[i]==null)
				return i;
	} else {
		for (int i = 0; i < size; i++)
			if (o.equals(elementData[i]))
				return i;
	}
	return -1;
}

     3. indexOf() in LinkedList.java

/**
 * Returns the index of the first occurrence of the specified element
 * in this list, or -1 if this list does not contain the element.
 * More formally, returns the lowest index {@code i} such that
 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
 * or -1 if there is no such index.
 *
 * @param o element to search for
 * @return the index of the first occurrence of the specified element in
 *         this list, or -1 if this list does not contain the element
 */
public int indexOf(Object o) {
	int index = 0;
	if (o == null) {
		for (Node<E> x = first; x != null; x = x.next) {
			if (x.item == null)
				return index;
			index++;
		}
	} else {
		for (Node<E> x = first; x != null; x = x.next) {
			if (o.equals(x.item))
				return index;
			index++;
		}
	}
	return -1;
}

    It is found that the implementation of the List interface, whether it is "ArrayList" or "LinkedList", matches the equals() method. Therefore, rewrite the equals method of "OrderForm" in the example:

package exec;

import java.util.Random;

public class OrderForm {
	
	private Long id;
	private String name;
	private Random score;
	private String group;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Random getScore() {
		return score;
	}
	public void setScore(Random random) {
		this.score = random;
	}
	public String getGroup() {
		return group;
	}
	public void setGroup(String group) {
		this.group = group;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false ;
		}
		if (obj instanceof OrderForm){
			OrderForm bwAutoLoanEmpDailyForm = (OrderForm) obj;
			if(bwAutoLoanEmpDailyForm.id.longValue() == this.id.longValue()){
				return true ;
			}
		}
		return false ;
	}
}

    At this point, undo "code_piece_2" to solve this problem perfectly.


Addition:
     1. When rewriting the equals() method, to judge the equality of two Long-type values, remember to use "==" directly, which can be solved in the form of .longValue(). Of course, "==" is in java There are many pits, which data types cannot be judged by "==", and look forward to the future summary.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325565483&siteId=291194637