Java collection framework [list / set]

1. Basic introduction:

7. Use LinkedList to realize the stack and queue structure, that is, the use of its unique addfirst, addlast and remove methods. Just note that the elements added and deleted in LinkedList are objects rather than general objects. It should be said that all things in the collection framework accept object objects, so pay attention to it when writing specific functions

8. Use ArrayList to write several applets. The first is to use ArrayList to remove duplicate elements, in which the elements are strings, and the second is to remove some custom objects. The second program also reveals that the interface for comparing the elements in the list collection is contains. Its bottom layer is the equals method of the called object, and for remove, it is also the bottom layer that calls the equals method to compare and delete. So the point is to rewrite the equals method. In addition, every time the next method is used in the iterator, the judgment of hasnext must be made, otherwise the element may not be found. For example, when there are two next methods in a hasnext and the elements are odd, exceptions will be thrown

        class Person{
            private String name;
            private int age;
            Person(String name,int age){
                this.name=name;
                this.age=age;
            }
            String getName(){
                return this.name;
            }
            private int getAge(){
                return this.age;
            }
            public boolean equals(Object object){
                if (!(object instanceof Person)){
                    return false;
                }
                Person person=(Person)object;  //注意这个地方必须要强转否则会出现下面的person无法调用方法
                return this.name.equals(person.getName()) && this.age==person.getAge();
            }
        }
        public class ArrayList_7 {
            private static ArrayList<Person> singleElement(List<Person> al){
                ArrayList<Person> newAl=new ArrayList<Person>();
                Iterator<Person> it=al.iterator();
                while (it.hasNext()){
                    Person tmp= it.next();  //iterator返回的是object所以必须要强转
                    if (!newAl.contains(tmp)){
                        newAl.add(tmp);
                    }
                }
                return newAl;
            }

            public static void main(String[] args) {
                ArrayList<Person> al=new ArrayList<>();
                al.add(new Person("zhang01",1));
                al.add(new Person("zhang02",2));
                al.add(new Person("zhang03",1));
                al.add(new Person("zhang03",1));
                al=singleElement(al);
                for (Person per : al) {   //可以使用这种更好的语言结构来实现迭代省去了iterator迭代 也不用考虑向下类型转换
                    System.out.println(per.getName());
                }
            }
        }

9. The elements stored in the set are unordered, and the elements inside are non repeatable. Obviously, if only the string is stored, it is easy to know whether it is repeated, which is unordered. We judge whether it is repeated by ourselves. The public methods in set are the methods common to the collection framework. The important ones are its subclasses. Here are two methods, HashSet and TreeSet

When storing general custom objects, we find that if we want some objects with consistent attributes as duplicate objects, HashSet itself cannot do so. Therefore, we need to understand the underlying layering principle of HashSet. The underlying layer of HashSet is the hash table, When storing elements, first judge whether the hashcode values of the stored elements are the same, that is, call their hashcode method. Note that hashcode is the method of object object, so all objects have this method. In addition, if their hashcodes are the same, then call their equals method If it is different, it will be saved in, and if it is the same, it will be kicked out. To put it bluntly, the bottom layer of HashSet judges whether it is a duplicate element. The first is to judge their hashcode, and the second is the equals method. If you want to customize how the object is stored, you must rewrite these two methods, but you must pay attention to their parameter list when rewriting, otherwise it will not take effect, Generally speaking, hashcodes of different objects should not be consistent, resulting in redundant comparison

The hashcode and equals methods are used to determine whether an element exists and delete an element

The following is a code example of HashSet:

  class People{
      private String name;
      private int age;

      People(String name,int age){
          this.name=name;
          this.age=age;
      }

      String getName(){
          return this.name;
      }

      private int getAge(){
          return this.age;
      }

      public int hashCode(){
          return name.hashCode()+age;
      }

      public boolean equals(Object object){
          if (!(object instanceof People)){
              return false;
          }
          People person=(People)object;  //注意这个地方必须要强转否则会出现下面的person无法调用方法
          return this.name.equals(person.getName()) && this.age==person.getAge();
      }

  }

  public class HashSet_8 {
      public static void main(String[] args) {
          HashSet<People> hs=new HashSet<People>();
          hs.add(new People("1",11));
          hs.add(new People("2",11));
          hs.add(new People("1",11));
          for (People pe:hs){
              System.out.println(pe.getName());
          }
      }
  }

10. TreeSet means that the elements in the collection will be sorted automatically. If it is a string, they can be compared automatically, because the string has implemented the comparable interface. However, if you want to store general element objects, you must make the modified class implement the comparable interface, because this interface will force the class to be comparative, and then copy the CompareTo method in this interface, If greater than returns a positive number equal to zero and less than, it will be negative. Note that if there are multiple sorting elements, then judge the equality condition during comparison. Pay attention to the judgment of other sorting elements, otherwise a condition is equal but not the same element and cannot be saved

class Student implements Comparable{
 private String name;
 private int age;

 Student(String name,int age){
     this.name=name;
     this.age=age;
 }

 public String getName() {
     return name;
 }

 public int getAge() {
     return age;
 }

 @Override
 public int compareTo(Object o) {
     if (!(o instanceof Student)){
         throw new RuntimeException("not same type");
     }
     if (this.age>((Student) o).age){
         return 1;
     }else if (this.age==((Student) o).age){
         return this.name.compareTo(((Student) o).name);
         //注意多重判断,要是age一样的话他们就会被当成相同元素而无法插入  string类已经实现了comparable接口
         //其实java中很多类都实现了comparable接口,让类具有可比性
     }
     return -1;
 }
}

public class TreeSet_9 {
 public static void main(String[] args) {
     TreeSet<Student> ts=new TreeSet<>();
     ts.add(new Student("ab",1));
     ts.add(new Student("kb",3));
     ts.add(new Student("mb",3));
     ts.add(new Student("am",7));
     for (Student stu :
             ts) {
         System.out.println(stu.getName()+"--------"+stu.getAge());
     }
 }
}

11. The underlying data structure of TreeSet is a binary tree. The arrangement of elements is that the first entered element is used as the root node, and then the left child or the right child is determined according to the value returned by the CompareTo method. Here, if the positive number returned by the CompareTo method is the right child, and the negative number is the left child, it means that the same element does not need to be compared. Therefore, whether the elements in the TreeSet are repeated or not is the return value of the CompareTo function. In this case, we can also specify that if a TreeSet is taken out or taken out in reverse order, CompareTo returns all 1 or - 1. Of course, if the return is always 0, only one element in the last set is the first element

12. In TreeSet, in addition to implementing the comparable interface and copying the CompareTo method, another sorting method is the comparator. The previous comparable interface makes the elements comparative, while the comparator makes the collection comparative. This priority is higher. The specific method is to pass in a user-defined comparator when the collection is instantiated, That is, the construction method passes in a comparator object, which is also an interface. To instantiate, you need to implement its compare method, and the comparator is also more commonly used


class MyComparator implements Comparator{

 public int compare(Object o1,Object o2){
     Student obj1=(Student)o1;
     Student obj2=(Student)o2;
     int num=obj1.getName().compareTo(obj2.getName());
     if (num==0){
        return new Integer(obj1.getAge()).compareTo(obj2.getAge());
     }
     return num;
 }
}

public class TreeSet_10 {
 public static void main(String[] args) {
     TreeSet<Student> ts=new TreeSet<Student>(new MyComparator());
     ts.add(new Student("dsf",11));
     ts.add(new Student("dmf",12));
     ts.add(new Student("ddf",13));
     ts.add(new Student("jf",14));
     for (Student stu :
             ts) {
         System.out.println(stu.getName()+"----------"+stu.getAge());
     }
 }
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>