The second part of JAVA basic learning -- array, string class, set class

Keywords: Java less JDK

Here we undertake Contents of the previous part

Let's learn about array, string class and collection class of Java language

array 80

Java's array concept is similar to C + +, it should be noted that array is an object

One-dimensional array

  • Directly specify the initial value to create an array object:
int [] a1={23,-9,38,8,65};
  • Creating an array object with the keyword new
int a[];
a=new int[9];

Bubble sorting with one dimensional array

package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class SortClass                //Class definition start
{
	void sort(int arr[])          //Start bubble sorting
	{
		int i,k,temp;
		int len=arr.length;
		for(i=0;i<len-1;i++)
		{
			for(k=len-1;k>i;k--)       //Detection from back to front (the arranged ones will pile up to the front)
			{
				if(arr[k]<arr[k-1])
				{
					temp=arr[k];
					arr[k]=arr[k-1];
					arr[k-1]=temp;
				}
			}
		}
	}
}
public class test
{
	public static void main(String []args) throws IOException
	{
		BufferedReader keyin=new BufferedReader(new InputStreamReader(System.in));
		int i;
		String C1;
		int arr[]=new int [8];
		int len=arr.length;
		System.out.println("Please enter 8 integers from the keyboard, only one number can be entered in a row");
		for(i=0;i<len;i++)
		{
			C1=keyin.readLine();         //Used to read a string
			arr[i]=Integer.parseInt(C1);          //Convert string type c1 to integer type			
		}
		//Print raw data
		System.out.println("raw data:");
		for(i=0;i<len;i++)
		{
			System.out.print(" "+arr[i]);
		}			
		System.out.println("\n");
		SortClass p1=new SortClass(); 
		p1.sort(arr);
		System.out.println("Results of bubble sorting:");
		for(i=0;i<len;i++)
		{
			System.out.print(" "+arr[i]);
		}
		System.out.println("\n");
		keyin.close();                   //Close this stream
	}
}

raw data:
2 354 5 -7 34 1 96 465

Results of bubble sorting:
-7 1 2 5 34 96 354 465

Add: the difference between print and println:

print: displays its parameters in the command window and positions the output cursor after the last character displayed.

println: display its parameters in the command window, add a line break at the end, and position the output cursor at the beginning of the next line.

Two-dimensional array

String class A kind of

String

package test;
import java.io.UnsupportedEncodingException;
public class test
{
	public static void main(String []args) throws UnsupportedEncodingException
	{
		//String of character array type
		char charArray[]= {'b','i','r','t','h',' ','d','a','y'};
		//A string of byte array type in which the value of each byte represents the international internal code of Chinese characters
		//The international internal code of Chinese characters (GB 2312 code), two byte code to form a Chinese character
		//The array constitutes four Chinese characters of "Object-Oriented". -The Chinese characters composed of 61 and - 26 are "face", and so on
		byte byteArray[]= {-61,-26,-49,-14,-74,-44,-49,-13};
		StringBuffer buffer;   //Declare reference variables for string objects
		String s,s1,s2,s3,s4,s5,s6,s7,ss;       //Declare reference variables for string objects
		s=new String("hello"); //Create a string object "hello" with s pointing to it
		ss="ABC";            //Create a string object "ABC" with ss pointing to it
		//Creating a string object with StringBuffer
		buffer=new StringBuffer("Welcome to Java Program!");
		s1=new String();          //Create an empty string object
		s2=new String(s);        //Create a new String object "hello", s2 points to the object
		s3=new String(charArray);  //Using character array to create string object "birth day", s3 points to the object
		//Create the string object "day" with 3 characters starting with subscript 6 in the string array
		s4=new String(charArray,6,3);
		//Using string array byteArray to create "Object-Oriented" string object according to GB2313 coding scheme
		s5=new String(byteArray,"GB2312");
		//Starting from the byte with subscript 2 of byteArray array created previously, take 4 consecutive bytes,
		//That is, take {- 49, - 14, - 74, - 44} to create a string object
		s6=new String(byteArray,2,4,"GB2312");
		//Create a new String object "welcome to the Java program! ", s7 points to the object
		s7=new String(buffer);
		System.out.println("s1="+s1);
		System.out.println("s2="+s2);
		System.out.println("s3="+s3);
		System.out.println("s4="+s4);
		System.out.println("s5="+s5);
		System.out.println("s6="+s6);
		System.out.println("s7="+s7);
		System.out.println("ss="+ss);
		System.out.println("buffer="+buffer);
	}
}

s1=
s2=hello
s3=birth day
s4=day
s5 = object oriented
s6= to right
s7 = welcome to Java program!
ss=ABC
buffer = welcome to Java program!

Common methods of String class

int length() returns the length of the current string object

char charAt (int index) returns the character at the index of the current string subscript

int indexOf(int ch) returns the index of the first occurrence of a specified character in this string

String subString(int beginIndex) returns the substring from beginIndex to the end of the current string

boolean equals(Object obj) compares this string with the specified object

String replace(char oldCh,char newCh)

static String valueOf(type variable) returns the string form of variable. Type is the basic type

String toString() returns the current string

StringBuffer class

StringBuffer is a String buffer class. Unlike String class, StringBuffer class is a String class whose content can be changed in operation. That is, once the object of StringBuffer class is created, the content of String can be changed and changed in operation.

package test;
import java.io.UnsupportedEncodingException;
public class test
{
	public static void main(String []args) throws UnsupportedEncodingException
	{
		StringBuffer buf1=new StringBuffer(); //Create an empty string buffer with an initial length of 16 that buf1 points to
		StringBuffer buf2=new StringBuffer(10); //Create an empty string buffer with an initial length of 10 pointed by buf2
		StringBuffer buf3=new StringBuffer("hello"); //Creates a string buffer with the specified "hello" string
		//Returns the current string length
		int len1=buf1.length();
		int len2=buf2.length();
		int len3=buf3.length();
		//Returns the current buffer length
		int le1=buf1.capacity();
		int le2=buf2.capacity();
		int le3=buf3.capacity();
		//Take the character marked 3 from buf3 string
		char ch=buf3.charAt(3);
		//Use the toString method of StringBuffer to convert three StringBuffer objects to String object output
		System.out.println("buf1 Contents:"+buf1.toString());
		System.out.println("buf2 Contents:"+buf2.toString());
		System.out.println("buf3 Contents:"+buf3.toString());
		System.out.println("buf1 String length of:"+len1);
		System.out.println("buf2 String length of:"+len2);
		System.out.println("buf3 String length of:"+len3);
		System.out.println("buf1 Buffer length for:"+le1);
		System.out.println("buf2 Buffer length for:"+le2);
		System.out.println("buf3 Buffer length for:"+le3);
		System.out.println("buf3 The third character of:"+ch);
	}
}

buf1 content:
Content of buf2:
buf3 content: hello
String length of buf1: 0
String length of buf2: 0
String length of buf3: 5
Buffer length of buf1: 16
Buffer length of buf2: 10
Buffer length of buf3: 21
The third character of buf3: l

Collection class Accession

Collection interface:

As the root of the Collection hierarchy, Collection can store elements in the form of Set or List. The JDK does not provide any direct implementation of the Collection interface, but through its sub interfaces (such as Set and List)

Common basic operations are as follows:

boolean add(Object obj)         //Add an element
boolean addAll(Collection c)      //Add all elements in a collection
boolean remove(Object obj)         //Delete an element
boolean removeAll(Collection c)         //Delete all elements in a collection
void clear()    //Empty, delete all elements
boolean retainAll(Collection c)        //Take the same element from two sets
int size()       	//Get the number of elements in the collection
boolean isEmpty()     	//Determine whether the set is empty
boolean contains(Object o)        //Determine whether the specified element is included
boolean containsAll(Collection c)          //Determines whether to include all elements of the specified set in the parameter
Object[]  toArray()                //Returns an array containing all elements in this Collection
/*Returns an array containing all elements in this Collection; returns the runtime type of the array and the runtime type of the specified array
 The same. Note that you cannot directly convert a collection to an array of basic data types (for example, int, char), because the collection must hold
 There are objects. Where t in < T > represents a variable of generic type whose value can be any type passed (for example, Integer
,Character,Self defined objects, etc.), but it cannot be any basic data type (such as int, char)*/
<T>T[]      toArray(T[] a)         
terator iterator()               //Traverse each element in the Collection

Iterator iterator:

For each structure

Format of for each structure:

for(Object o:collection)System.out.println(o);          //Indicates that each line outputs an element

Iterator (iterator)

The Collection interface extends the Iterator interface. The iteration() method in the Collection interface returns an Iterator object through which each element in the Collection collection can be accessed one by one. Typical usage is as follows:

Iterator it=collection.iterator();           //Create an iterator object
while(it.hasNext())                    //The hasNext() is used to determine whether the next element exists in the iterator
{
        Object obj=it.next();          //Take down an element
}

Code example:

package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class test 
{
	public static void main(String []args)
	{
		Character[] c= {'A','B','C','D','E'};     //Create a c array whose element is a character object
		System.out.print("The output element is the c array");
		for(int i=0;i<c.length;i++)
		{
			System.out.print(c[i]+",");
		}
		System.out.println();                 //Another row
		//Create ArrayList and transform to Collection
		//Arrays.asList(c) indicates that the elements of C array are ArrayList elements
		//Here is a generic construct
		Collection<Character> c1=new ArrayList<Character> (Arrays.asList(c));
		c1.add('f');                //Add an element  
		System.out.println("Add in output set f Post element"+c1);
		c1.remove('B');              //Delete an element
		System.out.println("Using iterator output set to delete B All elements after");
		Iterator<Character> it=c1.iterator();     //Create an iterator object
		while(it.hasNext())              //Determine if the next element exists
		{ 
			Character i=it.next();     //Take down an element
			System.out.print(i+",");
		}
		System.out.println();
		Object[] cc=c1.toArray();      
		System.out.print("Output all elements of the array after the collection is transferred to the array:");
		for(Object ac:cc)         //Cycle of foreach structure
			System.out.print(ac+",");
		System.out.println();
	}
}

The output element is c array A,B,C,D,E of character object,
The elements [A, B, C, D, E, f] after adding f to the output set
Using iterator output set to delete all elements after B
A,C,D,E,f,
All elements of the array after the output set is transferred to the array: A,C,D,E,f,

List interface and implementation class:

The List interface inherits the Collection interface.

The common classes to implement List are ArrayList class and LinkedList class (these two classes have no synchronization method. If multiple threads access a List at the same time, they must synchronize their access).

  • ArrayList: an array is used to store the elements of a linear table. It is the sequential storage structure of a linear table. The main difference between JAVA array and array is that the size of array as container is immutable, while the size of ArrayList as container is variable.

Special operations added in List interface

void add(int index,E elemtype)        //Insert an element to the specified location
boolean addAll(int index,Collection<? extends E> c)    //Insert all elements in the collection to the specified location
//In the above, < extension E > indicates that the unknown type is a subtype of E or an E type
E remove(int index)              //Delete the element at the specified location in the list
E get(int index)                  //Returns the element at the specified location in the list
int indexOf(Object o)            //Gets the subscript of the first occurrence of the specified element in the list, and returns - 1 if it does not exist
int lastIndexOf(Object o)      //Gets the subscript of the last specified element in the list, and returns - 1 if it does not exist
E set(int index,E elemtype)        //Replace the element at the specified location in the list with the specified element
ListIterator<E> listIterator()         //List iterator
ListIterator<E> listIterator(int index)         //Iterate from the specified location in the list
  • LinkedList uses a linked storage structure to store elements in a linear table. According to the characteristics of linked storage structure, it is suitable for the insertion and deletion of elements.

LinkedList specific operation methods

void addFirst(E e)      //Inserts the specified element at the beginning of this list
void addLast(E e)      //Add the specified element to the end of this list
boolean offerFirst(E e)     //Inserts the specified element at the beginning of this list
boolean offerLast(E e)      //Inserts the specified element at the end of this list
E removeFirst()          //Remove and return the first element of this list
E removeLast()        //Remove and return the last element of this list
E pollFirst()            //Gets and removes the first element of this list and returns null if it is empty
E pollLast()            //Gets and removes the last element of this list and returns null if it is empty
E getFirst()              //Returns the first element of this list
E getLast()                //Returns the last element of this list
void push(E e)           //Push elements onto the stack represented by this list
E pop()                  //Pop an element from the stack represented by this list
E peek()                   //Gets but does not remove the header of this list

Set interface:

Introduction to Set interface:

Set is a Collection that does not hold duplicate elements. The common classes that implement the set interface are the HashSet, LinkedHashSet, and TreeSet classes (note that there is no synchronization mechanism for these three classes when using)

  • HashSet class. HashSet uses hashCode algorithm (hash function) to store functions, and the storage order of elements is independent of the insertion order. HashSet is a Set implemented for fast lookup.
  • TreeSet class. TreeSet class uses red black tree data structure to sort elements, which is a Set to ensure the alphabetical order of elements. Its search speed is slower than HashSet.
  • LinkedHashSet. Linkedhashset is a subclass of HashSet. It uses hash internally to speed up searching, and uses linked list to maintain sorting of elements.

Comparison of output results of code implementation of HashSet, LinkedHashSet and TreeSet

package test;
import java.util.*;
public class test 
{
	public static void main(String []args)
	{
		LinkedHashSet<String> s1=new LinkedHashSet<String> ();
		HashSet<String> s2=new HashSet<String> ();
		TreeSet<String> s3=new TreeSet<String> ();
		String[] str= {"B","A","C","D"};
		//Create ArrayList and transform to Collection 
		//Arrays.asList(c) indicates that the elements of C array are ArrayList elements
		Collection<String> list=new ArrayList<String> (Arrays.asList(str)); 
		//Add all the elements of the list to the three Set combinations
		s1.addAll(list);
		s2.addAll(list);
		s3.addAll(list);
		System.out.println("s1="+s1);
		System.out.println("s2="+s2);
		System.out.println("s3="+s3);
	}
}

s1=[B, A, C, D]
s2=[A, B, C, D]
s3=[A, B, C, D]

Interestingly, the HashSet has been sorted. The reason is quite complicated. I found a CSDN blog of Daxin. For those who want to know more about it, please have a look https://blog.csdn.net/he37176427/article/details/98054668

SortedSet interface:

SortSet interface is a sub interface of Set interface, which maintains its elements in ascending order. It sorts (natural sort) according to the natural order of elements, or it sorts (custom sort) according to the Comparator provided when creating SortedSet. The class that implements the SortedSet interface is the TreeSet class. In addition to inheriting the operation of Set interface, SortedSet interface also provides the following operations:

//Returns the comparator that sorts the elements in this Set, or null if the Set uses the natural ordering of its elements.
//Where <? Super E > indicates that the unknown type is a supertype of E or an E type
Comparator<? super E> comparator()  
E first()        //Returns the first element in the collection
E last()          //Returns the last element in the collection
//Returns a subset of elements in this Set whose element value is less than toelement
SortedSet<E> headset(E toElement)   
//Returns the subset of this Set, from fromElement (inclusive) to toElement (exclusive)
SortedSet<E> subset(E fromElement,E toElement)   

Simple operation with SortedSet

package test;
import java.util.*;
public class test 
{
	public static void main(String []args)
	{
		//Implement SortedSet interface
		SortedSet<String> set1=new TreeSet<String> (); 
		String[] str= {"B","A","C","D"};
		Collection<String> list=new ArrayList<String> (Arrays.asList(str));
		set1.addAll(list);        //Add all s1 elements to s2
		System.out.println("set1="+set1);  //Direct output set
		System.out.println("headSet('C')="+set1.headSet("C"));  //Returns a subset less than C
		System.out.println("subSet('B','D')="+set1.subSet("B","D"));//Returns a subset between B and D
		System.out.println("first="+set1.first()); //Returns the first element
		System.out.println("last="+set1.last());  //Returns the last element
	}
}

set1=[A, B, C, D]
headSet('C')=[A, B]
subSet('B','D')=[B, C]
first=A
last=D

Map interface:

The map interface has no inheritance relationship with the Collection interface. Map as a set of maps, each element contains key value (key value pair).

The value object in the Map can be repeated, but the key cannot be repeated. The common classes used to implement the Map interface are HashMap, TreeMap and LinkedHashMap classes. There is no synchronization mechanism for these three classes.

Common operations of Map interface:

V put(K key,V value)       //Associate the specified value value with the specified key in this map
V remove(Object key)      //If there is a key mapping, remove it from this mapping
void putAll(Map<? extends K,? extends V> m)     //Copies all mapping relationships from the specified map to this map
void clear()       //Remove all mapping relationships from this mapping
V get(Object key)       //Returns the value mapped by the specified key, or null if not
boolean containsKey(Object key)    //Determine whether the keyword key exists in the mapping relationship
boolean containsValue(Object value) //Determine whether there is value value in the mapping
int size()               //Returns the number of key value mapping relationships in this mapping
boolean isEmpty()               //Determine whether the mapping relationship exists
Set<K> keySet()    //Returns the Set view of the key contained in this map
Collection<V> values()           //Returns the Collection view of the values contained in this map
Set<Map.Entry<K,V>> entrySet()  Returns the Set view

Common operations of Map.Entry interface:

Map.Entry is an interface defined in map, which is specially used to store key value pairs. Common methods are as follows:

K getKey()   //Return the key corresponding to this item
V getValue()   //Return the value corresponding to this item
V setValue(Object value)      //Replace the value corresponding to this item with the specified value
boolean equals(Object ob)      //Compare the equality between the specified object ob and this item
Map.entrySet()         //Return mapped Set view

Add element and read element operations of Map:

package test;
import java.util.*;
public class test 
{
	public static void main(String []args)
	{
		Map<String,String> map=new HashMap<String,String>();
		map.put("book", "Java");
		map.put("Student", "Jacky Cheung");
		map.put("class", "333");
		System.out.println("map="+map.toString());    //Output map
		if(map.containsKey("book")) //If the existing key is "book"
		{
			System.out.print("lookup key=Books exist     ");
			String val=map.get("book");
			System.out.println("The value corresponding to the key "book" is:"+val);
		}
		else
			System.out.println("Search key "book", does not exist");
		//Output all key s
		Set<String> keys=map.keySet();          //Get all the key s
		Iterator<String> iter1=keys.iterator(); 
		System.out.print("All-out key: ");
		while(iter1.hasNext())
		{
			String str=iter1.next();
			System.out.print(str+",");
		}
		Collection<String> values=map.values();      //Get all the value s
		Iterator<String> iter2=values.iterator(); 
		System.out.print("\n All-out value:");
		while(iter2.hasNext())
		{
			String str=iter2.next();
			System.out.print(str+",");
		}
		System.out.println();
	}
}

map = {student = Jacky Cheung, class = 333, book = Java}
Find the key = book, and the value corresponding to the existing key "book" is: Java
All key s: students, classes, books
All value s: Zhang Xueyou, 333, Java

SortedMap interface:

SortedMap interface is a sub interface of Map interface, and it is a sort Map. All subclasses that implement this interface belong to sorting subclasses. The commonly used class to implement this interface is the TreeMap class. In addition to inheriting the operation of Map interface, SortedMap also provides some extension methods:

Comparator<? super K> comparator()       //Return comparator object
K firstKey()          //Returns the key of the first element
SortedMap<K,V>  headMap(K toKey)   //Returns a partial set less than or equal to the specified K
K lastKey()            //Returns the key of the last element
SortedMap<K,V> subMap(K fromKey,K toKey)  //Returns the collection of the specified Key range
SortedMap<K,V> tailMap(K fromKey)      //Returns a partial set larger than the specified Key

Simple operation with TreeMap

package test;
import java.util.*;
public class test 
{
	public static void main(String []args)
	{
		SortedMap<String,String> smap=new TreeMap<String,String>();
		smap.put("D", "04");
		smap.put("A", "01");
		smap.put("C", "03");
		smap.put("B", "02");
		System.out.println("sortMap="+smap);
		System.out.println("headMap('C')="+smap.headMap("C"));
		System.out.println("subMap('B','D')="+smap.subMap("B","D"));
		System.out.println("first()="+smap.firstKey());
		System.out.println("last()="+smap.lastKey());
	}
}

Collections algorithm class:

Unlike the Collection interface, the Collections class is an algorithm class, which further provides a series of static methods

  • addAll() method to add elements to a collection
addAll(Collection<? super T> c,T ...elements )

Add all specified elements to the specified Collection, and accept variable parameters

Example:

Collections.addAll(Collection aggregate,"B","A","E");
Collections.addAll(Collection aggregate,"C","F");
  • sort() and reverse() methods
sort(List<T> list)   //Arrange elements in ascending order according to their natural order
reverse(List<?> list)  //Reverses the ordering of elements in the specified list
sort(List<T> list,Comparator<? super T> c)  //Sort by comparator
  • shuffle() method of mixed arrangement (shuffle operation)
void shuffle(List<?> list)  //Arranges the specified list using the default random source
void shuffle(List<?> list,Random md)   //Arrange the specified list with random sources specified by md
  • replaceAll() method to replace a collection element
replaceAll(List<T> list,T oldVal,T newVal)  //Replace all oldVal in the list with newVal
  • Binary search of binary search
//Binary search search list to get the object specified by key
binarySearch(List<? extends Comparable<? super T>> list,T key)
//After sorting according to the comparer specified by c, binary search elements
binarySearch(List<? extends  T> list,T key,Comparator<? super T> c)

Binary search supplement: if the list does not contain a search key, a negative integer value is returned, which is "- insertpoint-1". Insertpoint means that the search key may be inserted into the bit of the list. If all elements in the list are smaller than the search key, the insertpoint is list.size()

  • swap method of exchanging specified element location
swap(List<?> list,int i,int j)   //Swap the positions of i and j in the List

 

 

 

This one is written here first, digest it for a few days and then write the later content

 

 

I hope it helps you

Welcome to my blog:: is-hash.com

For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source

Published 13 original articles, won praise 1, visited 2393
Private letter follow

Posted by joel24 on Sat, 07 Mar 2020 03:20:01 -0800