Java Basics learning 22Set collections

“This is the 22nd day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

About the author

  • The authors introduce

🍓 blog home page: author’s home page 🍓 Introduction: JAVA quality creator 🥇, a junior student 🎓, participated in various provincial and national competitions during school, and won a series of honors


Set Interface Introduction

The main difference between a Set interface and a List interface is that the content cannot be repeated

The set interface does not extend the Collection interface, while the List interface extends the Collection interface. Due to JDK1.8, the collection interface also provides some default methods that are not present in the Set interface. In other words, it is not possible to use get() in the set interface, but in the set subclass HashSet, TreeSet.

Hash store subclass: HashSet

Hash is an algorithm that, at its core, refers to a null-saving algorithm, so whenever a Hash is seen it means that it is saved in no order.

Observe the use of the Set interface

package com.day17.demo;

import java.util.HashSet;
import java.util.Set;

public class HashSetDemo {
	public static void main(String[] args) {
		Set<String> all = new HashSet<>();
		all.add("Hello");
		all.add("zsr");
        all.add("zsr");
		all.add("Abc"); System.out.println(all); }}Copy the code

After saving the data, it is found that the duplicate data is gone, and the data itself is saved in any order.

Sort store subclass: TreeSet

If you now want the data stored in a Set to be sequential, instantiate the Set interface via TreeSet.

Instantiate the interface using TreeSet

package com.day17.demo;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class HashSetDemo {
	public static void main(String[] args) {
		Set<String> all = new TreeSet<>();
		all.add("C");
		all.add("C");
		all.add("A");
		all.add("B");
		all.add("D"); System.out.println(all); }}Copy the code

Now you see that all the saved data is not duplicated and is in order. TreeSet is done using an ascending pattern.

Instructions on TreeSet sorting

As you can see from the previous program, all data stored in the TreeSet instantiation Set interface is in order. In this case, what about using a custom class?

The class must implement the Comparable interface and set the Comparable rule if its objects are to be sorted, but in this case it is important to note that, once Comparable is used, all the attributes in the class must be written into the sort.

Custom sort

package com.day17.demo;

import java.util.Set;
import java.util.TreeSet;
class Personn implements Comparable<Personn>{
	private String name;
	private Integer age;
	
	public Personn(String name, Integer age) {
		this.name = name;
		this.age = age;
	}
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge(a) {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString(a) {
		return "person [name=" + this.name + ", age=" + this.age + "]\n";
	}
	@Override
	public int compareTo(Personn o) {
		// TODO Auto-generated method stub
		if(this.age > o.age){
			return 1;
		}else if (this.age < o.age){
			return 0;
		}else{
			return this.name.compareTo(o.name); }}}public class TreeSetDemo {
	public static void main(String[] args) {
		// TODO automatically generates method stubs
		Set<Personn> all=new TreeSet<Personn>();
		all.add(new Personn("Zhang".20));
		all.add(new Personn("Zhang".20));
		all.add(new Personn("Bill".20));
		all.add(new Personn("Fifty".30));
		all.add(new Personn("Daisy".40)); System.out.println(all); }}Copy the code

Because TreeSet was too cumbersome to use in real life, the simple Java classes developed in the project were based on the design of database tables, and if a table had too many fields, your class would have to be written to death.

The TreeSet subclass depends on whether the return value of the Compara() method is 0 to determine if it is a repeated element.

A note on repeating elements

The Comparable interface is used to determine duplicate elements when using the TreeSet subclass for data preservation. This is not the entire Set interface’s way of determining duplicate elements, because if you subclass HashSet, and its Comparable has no relation to its Comparable, there are two main methods for determining duplicate elements:

  • Hash code: public int hashCode();
  • Public Boolean equals(Object obj)

During object comparisons, hashCode() is first compared with the hashCode() of the objects stored in the collection, if the codes are the same, then equals() is used to compare the contents, if all are the same, the same elements.

package com.day17.demo;

import java.util.Set;
import java.util.TreeSet;
class Personn implements Comparable<Personn>{
	private String name;
	private Integer age;
	
	public Personn(String name, Integer age) {
		this.name = name;
		this.age = age;
	}
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge(a) {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	@Override
	public int hashCode(a) {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null)?0 : age.hashCode());
		result = prime * result + ((name == null)?0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if(getClass() ! = obj.getClass())return false;
		Personn other = (Personn) obj;
		if (age == null) {
			if(other.age ! =null)
				return false;
		} else if(! age.equals(other.age))return false;
		if (name == null) {
			if(other.name ! =null)
				return false;
		} else if(! name.equals(other.name))return false;
		return true;
	}
	@Override
	public String toString(a) {
		return "person [name=" + this.name + ", age=" + this.age + "]\n";
	}
	@Override
	public int compareTo(Personn o) {
		// TODO Auto-generated method stub
		if(this.age > o.age){
			return 1;
		}else if (this.age < o.age){
			return 0;
		}else{
			return this.name.compareTo(o.name); }}}public class TreeSetDemo {
	public static void main(String[] args) {
		// TODO automatically generates method stubs
		Set<Personn> all=new TreeSet<Personn>();
		all.add(new Personn("Zhang".20));
		all.add(new Personn("Zhang".20));
		all.add(new Personn("Bill".20));
		all.add(new Personn("Fifty".30));
		all.add(new Personn("Daisy".40)); System.out.println(all); }}Copy the code

If you want to identify the uniqueness of objects, you must use hashCode() and equals() together.

Interview question: What happens if two hashCode() are the same and equals() are different? Not eliminate

Interview question: What happens if two hashCodes () are different and equals() are the same? Not eliminate

Object judgment must be implemented in both cases.

The output operation of the collection

Before this belong to the basic operations of a single value set, but for collection is one of the most important problem is how to set the content of output operations, and the problem in the Java class set framework gives the four kinds of output way: the Iterator, a ListIterator, Enumeration, foreach.

Iterator output: Iterator

public boolean hasNext() Determines if there is a next element
public E next() Get the current element
public default void remove() Remove elements

The standard Iterator

package com.day17.demo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ArrayListDemo {
	public static void main(String[] args) {
		List<String> all = new ArrayList<>();// Only String data can be stored in the set
		all.add("Hello");
		all.add("Hello");	// Duplicate data
		all.add("world~!");
		all.add("zsr~");
		Iterator<String> iter = all.iterator();// instantiate Iterator
		while(iter.hasNext()){ String str = iter.next(); System.out.println(str); }}}Copy the code

The remove() method provided by the Iterator interface mainly solves the problem of removing elements from collections

The remove operation

package com.day17.demo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ArrayListDemo {
	public static void main(String[] args) {
		List<String> all = new ArrayList<>();// Only String data can be stored in the set
		all.add("Hello");
		all.add("Hello");	// Duplicate data
		all.add("a");
		all.add("world~!");
		Iterator<String> iter = all.iterator();// instantiate Iterator
		while(iter.hasNext()){
			String str = iter.next();
			if("a".equals(str)){
				all.remove("a");// If the interrupt following this operation is executed
				//iter.remove(); Execute if subsequent output is not interrupted
				continue; } System.out.println(str); }}}Copy the code

In the future, whenever we see the output operation of the collection, we will always use the Iterator interface.

Bidirectional iteration output: ListIterator

ListIterator is a sub-interface of Iterator. ListIterator is a sub-interface of Iterator. ListIterator is a sub-interface of Iterator. ListIterator is a sub-interface of Iterator.

Public Boolean hasPrevious();

Retrieve the previous element: public E previous().

But if you want to get an instantiated object from the ListIterator interface, there is no such method for Collection. This method exists in the List interface:

Public ListIterator listIterator()

Perform bidirectional iteration

package com.day17.demo;


import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;


public class ListIteratorDemo {
	public static void main(String[] args) {
		// TODO automatically generates method stubs
		List<String> all=new ArrayList<String>();
		all.add("hello");
		all.add("hello");
		all.add("world");
		ListIterator<String> ite=all.listIterator();
		System.out.println("From front to back");
		while(ite.hasNext()){
			String str=ite.next();
			System.out.print(str + "、");
		}
		System.out.println();
		System.out.println("From back to front");
		while(ite.hasPrevious()){
			String str=ite.previous();
			System.out.print(str + "、"); }}}Copy the code

But for a back-to-front operation, a front-to-back output must occur before proceeding. Because only List is available for this output interface, it is almost never used in development.

Obsolete interface: Enumeration

Enumeration is one of the earliest output interfaces to be used as Enumeration outputs. It was introduced in JDK1.0 and expanded in JDK1.5 to include generics. There are only two methods defined in the Enumeration interface:

Public Boolean hasMoreElements() public Boolean hasMoreElements()

Public E nextElement()

Instead of relying on the Collection interface, we can rely on the Vector class. We define a method in the Vector subclass: Public Enumeration elements().

Use Enumertaion for output

package com.day17.demo;

import java.util.Enumeration;
import java.util.Vector;

public class IteratorTest {
	public static void main(String[] args) {
		// TODO automatically generates method stubs
		Vector<String> all=new Vector<String>();
		all.add("hello");
		all.add("hello");
		all.add("world");
		Enumeration<String> ite=all.elements();
		while(ite.hasMoreElements()){ String str=ite.nextElement(); System.out.println(str); }}}Copy the code

In terms of development, Enumeration is definitely not the first thing to think about; Iterator is definitely the first thing to think about, and only use it if you have to.

JDK1.5 supports foreach

For foreach output, in addition to the array output, we can also output collections.

Use the foreach

package com.day17.demo;

import java.util.ArrayList;
import java.util.List;

public class IteratorTest {
	public static void main(String[] args) {
		// TODO automatically generates method stubs
		List<String> all=new ArrayList<String>();
		all.add("hello");
		all.add("hello");
		all.add("world");
		for(String x : all){ System.out.println(x); }}}Copy the code

Using foreach is not a widely accepted form of action code.