java Collection Memory details and simple examples

  • 2020-06-19 10:25:15
  • OfStack

This article is just to strengthen the foundation of 1, recall 1 of the storage of these two commonly used things...

1. Collection

1. Storage objects can be considered: array combined

2. Array storage object features: Student[] stu = new Student[20]; stu [0] = new Stutdent (); ...

Disadvantages: 1 once created, its length cannot be changed
The number of objects in a real array is unknown

Set 3.

Collection interface
List interface: Store ordered, repeatable elements
--ArrayList (main implementation class, preferred)
--LinkedList (frequent insertion, deletion)
--Vector (ancient implementation class, thread safety)
Set interface: store unordered, non-repeatable elements, Set commonly used methods are defined by Collection
--HashSet (main realization class)
丨 -- -- -- -- -- -- -- LinkedHashSet
丨 -- -- -- -- -- -- -- TreeSet

Example: (Set interface)

1)HashSet

Set stores unordered elements that are not repeatable!

1. Disorder: Disorder! = randomness. True disorder refers to the unordered location of elements in the underlying storage. (Save according to hash value)

2. Non-repeatability: When the same element is added to Set, the latter cannot be added.


// Description: Request to be added Set The class in which the element in, 1 Need to rewrite equals () and hashcode () Methods. Ensuring that set Non repeatability of elements in !

How are the elements in set stored? Hash algorithm is used.

When you add an element to set, you first call the hashCode () method of the class in which the object is located and calculate the hash value of the object. This hash determines where the object is stored in set. If there is no object store before, the object is stored there. If there is an object stored, compare the two objects through equals () method to see if they are the same. If the last object is the same, it can't be added.

How about false? Are stored. (Not recommended)


//> Requirements: hashcode () The method should be with equals () method 1 Cause. 

The example code is as follows:


public class TestSet{

  @Test
  public void testHashSet(){
    Set set = new HashSet();
    set.add(123);
    set.add(456);
    set.add(new String ( "AA" ) );
    set.add(new String ( "AA" ) );// If you add the same element here, you don't add it. 
    set.add("BB");
    set.add(null);
    System.out.println(set.size());
    System.out.println(set);
  }
}

2) LinkedHashSet ()


/*
 *LinkedHashSet : Maintained with linked list 1 The order in which the two are added to the collection results as we traverse LinkedHashSet Set elements are based on  
 * Add in the order traversal! But the storage is unordered! 
 *LinkedHashSet Insert performance is slightly below HashSet But in iterative access Set All elements in have good performance. 
 *LinkedHashSet Collection elements are not allowed to repeat. 
 */
public class TestLinkedHashSet{

  @Test
  public void testLinkedHashSet(){
    Set set = new LinkedHashSet();
    set.add(123);
    set.add(456);
    set.add(new String ( "AA" ) );
    set.add(new String ( "AA" ) );
    set.add("BB");
    set.add(null);
    System.out.println(set.size());
    System.out.println(set);

    // Iterator to traverse 
    Iterator iterator = set.iterator();
    while(iterator.hasNext()){
      System.out.println(iterator.next());
    }
  }
}
 The output is :123,456,AA,BB,null

3)TreeSet


/*
 *1. to TreeSet The elements added in must be the same 1 A class of 
 *2. Can be traversed in the specified order of the elements added to the collection, like String , the wrapper class, etc., are traversed by default from small to large 
 *3. As to the TressSet When adding a custom class object, there are two sort methods: natural sort custom sort 
 *4. Natural ordering: Requires a custom class implementation java.lang.Comparable The interface overwrites it compareTo ( Object obj ) 
   In this method, specify which attribute to sort by the custom class amount. 
 *5. to TreeSet When you add an element to the compareTo () Make a comparison, 1 Once return 0 , although only two objects have the same subattribute value,    But the program will assume that the two objects are the same, and so on 1 Objects cannot be added. 
 *>compartTo() with hashCode(); As well as equals()3 Who keep 1 Cause! 
 */
False : 
public class TestTreeSet{
  // So the addition will be reported 1 a CastException , an exception will occur 
  @Test
  public void testTreeSet(){
    Set set = new TreeSet();
    set.add(123);
    set.add(456);
    set.add(new String ( "AA" ) );
    set.add(new String ( "AA" ) );
    set.add("BB");
  }
}
True : 
public class TestTreeSet{

  @Test
  public void testTreeSet(){
    Set set = new TreeSet();
//   set.add(new String ( "AA" ) );
//   set.add(new String ( "AA" ) );// The same element doesn't go in 
//   set.add("JJ");
//   set.add("GG");
//   set.add("MM");

    //String No mistake is thought String The type is implemented Comparable Interface, the sorting method has been overridden 

    // when Person Class is not implemented Comparable Interface, when to TreeSet add Person Object, report    //ClassCastException
    set.add(new Person("CC",23));
    set.add(new Person("MM",21));
    set.add(new Person("GG",25));
    set.add(new Person("JJ",24));
    set.add(new Person("KK",20));// New added 1 a KK , but age The same 
    set.add(new Person("DD",20));

    for(Object str : set){
      System.out.println(str);
    }
  }
}
 The output is AA,GG,JJ,MM


// As to the TreeSet add Person Based on this method, determine which attribute to order. 
// Needs to be rewritten compareTo methods 
//Person(name,age . get/set Method, empty constructor, toString,equals,hashCode)

  @Override
  public int compareTo(Object o){
    if(o instanceof Person){
      Person p = (Person)o;
    // return this.name.compareTo(p.name);   From small to big 
    // return -this.name.compareTo(p.name);   From big to small 
      int i = this.age.compareTo(p.age);
      if(i == 0){
        return this.name.compareTo(p.name);
      }else{
        return i ;
      }
    }
    return 0;
  }
// Custom sorting 

//Customer(name,id . get/set Method, empty constructor, toString,equals,hashCode)
public class TestTreeSet{

  @Test
  public void testTreeSet2(){
  //1. create 1 An implementation Comparator The class object of the interface 
    Comparator com = new Comparator(){
      //
      @Override
      public int compare(Object o1,Object o2){
        if(o1 instanceof Customer && o2 instanceof Customer){
          Customer c1 = (Customer)o1;
          Customer c2 = (Customer)o2;
          int i = c1.getId().compareTo(c2.getId());
          if(i == 0){
            return c1.getName().compareTo(c2.getName());
          }
          return i;
        }
        return 0;
      }
    };
    //2. Passes this object as a formal parameter to TreeSet In the constructor 
    TreeSet set = new TreeSet(com);
    //3. to TreeSet add Comparator The interface compare Object of the class involved in the method 
    set.add(new Customer("AA",1003));
    set.add(new Customer("BB",1002));
    set.add(new Customer("GG",1004));
    set.add(new Customer("CC",1001));
    set.add(new Customer("DD",1001));

    for(Object str : set){
      System.out.println(str);
    }
  }
}

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: