有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将arrayList中的元素相互比较

我有一个包含四个对象元素的数组列表,我需要将这些对象相互比较。我需要避免类似的对象比较,并在两个对象相同的情况下执行continue。我尝试了下面的代码,但它避免了常见的对象迭代。有人能给我推荐一种比较同一数组列表中元素的最佳方法吗

代码:

List<Student> studentInfo= new ArrayList<Student>();

 for (int i = 0; i < list.size(); i++)
            {
                for (int j = 0 ; j < list.size(); j++)
                {


                    if(list.get(i).getstudentId().equals(list.get(j).getstudentId())) 
                    continue;

                    }

                }

            }

共 (2) 个答案

  1. # 1 楼答案

    你可以使用冒泡排序算法,但是你可以根据自己的需要使用它来代替排序

    一个更优雅的比较方法是:

    public class Student {
    
        private String id;
    
        /**
         * @return the id
         */
        public String getId() {
            return id;
        }
    
        /**
         * @param id the id to set
         */
        public void setId(String id) {
            this.id = id;
        }
    
    
    
        @Override
        public boolean equals (Object otherObject){
            if(!(otherObject instanceof Student)){
                return false;
            }
            if(((Student)otherObject).getId().equals(this.id)){
                return true;
            }
            return false;
        }
    
    }
    

    在你们班:

    for(int i = 0; i< studentList.size(); i++){
        for(int j = i+1; j< studentList.size(); j++){
            if(studentList.get(i).equals(studentList.get(j))){
                continue;
            }
        }
    }
    
  2. # 2 楼答案

    您需要避免i==j的情况,在这种情况下,if将计算为true

    if(i != j && list.get(i).getstudentId().equals(list.get(j).getstudentId())) 
      break;
    

    如果希望在循环的出口处知道是否发现了重复项,则需要一个外部变量(比如布尔值,或者可能是一个显示重复项所在位置的int)