Home > Java > javaTutorial > body text

Traversal of Java Set collections and comparison of implementation classes (with code)

黄舟
Release: 2017-03-30 10:24:49
Original
1609 people have browsed it

This article mainly introduces relevant information about Java Set traversal of collections and comparison of implementation classes. Friends in need can refer to

Traversal and implementation of Java Set collections Comparison of implementation classes

The Set collection in Java is a Collection that does not contain duplicate elements. First, let’s look at the traversal method

package com.sort; 
 
import java.util.HashSet; 
import java.util.Iterator; 
import java.util.Set; 
 
/** 
 * 一个不包含重复元素的 collection。更确切地讲,set 不包含满足 e1.equals(e2) 的元素对 e1 和 e2, 
 * @author Owner 
 * 
 */ 
public class SetTest2 { 
 
  public static void main(String[] args) { 
    Set<String> set = new HashSet<String>(); 
     
    set.add("a"); 
    set.add("b"); 
    set.add("c"); 
    set.add("d"); 
    set.add("e"); 
     
    set.add("e");//不能放入重复数据 
     
    /** 
     * 遍历方法一,迭代遍历 
     */ 
    for(Iterator<String> iterator = set.iterator();iterator.hasNext();){ 
      System.out.print(iterator.next()+" "); 
    } 
     
    System.out.println(); 
    System.out.println("********************"); 
     
    /** 
     * for增强循环遍历 
     */ 
    for(String value : set){ 
      System.out.print(value+" "); 
    } 
  } 
}
Copy after login

Note: What is put in the Set collection here is String type, If we put in a self-defined class instance, such as a Person class instance, then we have to rewrite the hashcode and equal methods ourselves, use our own key fields to rewrite, because when When using HashSet, the hashCode() method will be called to determine whether the hash code value of the object already stored in the set is consistent with the hash code value of the added object; if it is inconsistent, add it directly; if If they are consistent, then compare the equals method. If the equals method returns true, it means that the object has been added, and no new object will be added, otherwise it will be added.

Let’s analyze another important implementation class of Set collection, TreeSet.

TreeSet uses the natural order of the elements to sort the elements. , or sorted according to the Comparator provided when the set was created, depending on the constructor used.

In layman terms, you can display according to the sorted list, or you can sort it according to the specified rules

Set<String> set = new TreeSet<String>(); 
     
    set.add("f"); 
    set.add("a"); 
    set.add("b"); 
    set.add("c"); 
    set.add("d"); 
    set.add("e"); 
     
    System.out.println(set);
Copy after login

Output: [a, b, c , d, e, f]

Output after sorting

So what if we want it to be output in reverse order? Of course there are many ways. Here I specify a rule to let him output in reverse order

package com.sort; 
 
import java.util.Comparator; 
import java.util.Iterator; 
import java.util.Set; 
import java.util.TreeSet; 
 
public class TreeSetTest3 { 
 
  public static void main(String[] args) { 
    Set<String> set = new TreeSet<String>(new MyComparator()); 
     
    set.add("a"); 
    set.add("b"); 
    set.add("c"); 
    set.add("d"); 
    set.add("e"); 
    set.add("A"); 
     
    for(Iterator<String> iterator = set.iterator();iterator.hasNext();){ 
      System.out.print(iterator.next()+" "); 
    } 
  } 
} 
 
class MyComparator implements Comparator<String>{ 
 
  @Override 
  public int compare(String o1, String o2) { 
     
    return o2.compareTo(o1);//降序排列 
  }
Copy after login

Output: e d c b a A

What if the Set collection puts a class type defined by ourselves?

Note: Be sure to define a sorting rule class that implements the Comparator interface, similar to the above method

package com.sort; 
 
import java.util.Comparator; 
import java.util.Iterator; 
import java.util.Set; 
import java.util.TreeSet; 
 
public class TreeSetTest2 { 
 
  public static void main(String[] args) { 
    Set<Person> set = new TreeSet<Person>(new PersonComparator()); 
     
    Person p1 = new Person(10); 
    Person p2 = new Person(20); 
    Person p3 = new Person(30); 
    Person p4 = new Person(40); 
     
    set.add(p1); 
    set.add(p2); 
    set.add(p3); 
    set.add(p4); 
     
    for(Iterator<Person> iterator = set.iterator();iterator.hasNext();){ 
      System.out.print(iterator.next().score+" "); 
    } 
  } 
} 
 
class Person{ 
  int score; 
   
  public Person(int score){ 
    this.score = score; 
  } 
   
  public String toString(){ 
    return String.valueOf(this.score); 
  } 
} 
 
class PersonComparator implements Comparator<Person>{ 
 
  @Override 
  public int compare(Person o1, Person o2) { 
     
    return o1.score - o2.score; 
  } 
   
}
Copy after login

Output: 10 20 30 40

If you arrange in reverse order of a person's score, you only need to change o2.score-o1.score

in the compare method.

The above is the detailed content of Traversal of Java Set collections and comparison of implementation classes (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template