Java-Object Array and Its Sorting and Finding Algorithms

Posted by Garion on Fri, 07 Jan 2022 18:27:18 +0100

array

Storing objects in arrays

In the previous section, we have described the creation and reference of arrays. Next, we mainly introduce the array storage objects, find objects, delete objects and common sorting algorithms.

Array elements can be of any type (as long as all elements have the same type), and in addition to the basic data type, elements of the array can also be objects of the class, such arrays are called object arrays.

Initialization of arrays is divided into static and dynamic initialization.

  • Static initialization: initialize array elements while declaring and defining arrays;
BankAccount[] accounts={new BankAccount("zhang",100.00)},
new BankAccount("li",2380.00),new BankAccount("wang",500.00);
  • Dynamic initialization: Allocate space for arrays using the operator new, which is formatted as follows for basic types of arrays;
type arrayName[]=new type[arraySize};
type[] arrayName=new type[arraySize];

For object arrays, the use of operator new simply allocates space to the array itself and does not initialize the elements of the array. That is, the array elements are empty, at this time no elements of the array can be accessed, and the array elements must be initialized before they can be accessed. So for object arrays, there are two steps;

First, space is allocated to the array, where each element is just a drink from the object.

type arrayName[]=new type[arraySize];

Each array element is then allocated space and its reference is assigned to the corresponding array element.

arrayName[0]=new type(paramList);
...
arrayName[arraySize-1]=new type(paramList);

Store student information for a class in an array

First declare Stude for Student Class;

  • Attributes include student number (id), name, English score (eng), math, computer score (comp), and total score (sum).
  • Methods include construction method, get method, set method, toString method, equals method, compare method, sum method.
import java.io.*;
public class Student {
    private String id;
    private String name;
    private int eng;
    private int math;
    private int comp;
    private int sum;
    //Construction method
    public Student(String id,String name,int eng,int math,int comp){
        this.id=id;
        this.name=name;
        this.eng=eng;
        this.math=math;
        this.comp=comp;
        sum();//Calculate total results
    }
    public Student(Student s){
        this.id=s.id;
        this.name=s.name;
        this.eng=s.eng;
        this.math=s.math;
        this.comp=s.comp;
        sum();//Calculate total results
    }
    public void setId(String id){
        this.id=id;
    }
    public void setName(String name){
        this.name=name;
    }
    public void setEng(int eng){
        this.eng=eng;
        sum();
    }
    public void setMath(int math){
        this.math=math;
        sum();
    }
    public void setComp(int comp){
        this.comp=comp;
        sum();
    }
    public String getId(){
        return id;
    }
    public String getName(){
        return name;
    }
    public int getEng(){
        return eng;
    }
    public int getMath(){
        return math;
    }
    public int getComp(){
        return comp;
    }
    public int getSum(){
        return sum;
    }
    void sum(){
        this.sum=eng+math+comp;
    }
    @Override//Represents overriding parent method
    public String toString(){
        return getId()+"\t"+getName()+"\t"+getEng()+"\t"+getMath()+"\t"+getComp()+"\t"+getSum();
    }
    @Override
    public boolean equals(Object x){
        if(this.getClass() !=x.getClass()){
            return false;
        }
        Student b=(Student) x;
        return (this.getId().equals(b.getId()));
    }
    //Comparing the result size, the current object's result is greater than the parameter object's result and returns 1, 0 when equal, and -1 for other objects
    public int compare(Student A){
        if(this.getSum()>A.getSum()){
            return 1;
        }
        else if(this.getSum()==A.getSum()){
            return 0;
        }else{
            return -1;
        }
    }
}

Next, declare the class class class;

  • Attributes include class name, capacity, students, and actual size.
  • Methods include construction method, get method, set method, toString method.

In order to persist the Student class object, that is, to store it on disk, it should be added to the serialization protocol to implement the Serializable interface.

public class StudentClass implements Serializable{
    private String name;
    static int capacity=40;
    private Student students[];
    private int size;

    public StudentClass(String name,int size){
        this.name=name;
        this.size=size;
        students=new Student[capacity];
    }
    public String getName(){
        return name;
    }
    public int getCapacity(){
        return capacity;
    }
    public Student [] getStudents(){
        return students;
    }
    public int getSize(){
        return size;
    }
    public void setName(String name){
        this.name=name;
    }
    public void setCapacity(int capacity){
        this.capacity=capacity;
    }
    public void setSize(int size){
        if(size>capacity){
            System.out.println("size by"+size+",+Cannot exceed"+capacity);
            return;
        }
        this.size=size;
    }
    public void setStudents(Student...students){
        for(int i=0;i<size;i++){
            this.students[i]=new Student(students[i]);
        }
        this.size=students.length;
    }
    @Override
    public String toString(){
        String s;
        s="Class:"+name+"\t"+"capacity"+capacity+"\t"+"Actual number of people:"+size+"\n\n";
        s=s+"School Number"+"\t"+"Full name"+"\t"+"English"+"\t"+"Mathematics"+"\t"+"Computer"+"\t"+"Total results\n";
        for(int i=0;i<size;i++){
            s=s+students[i].getId()+"\t"+students[i].getName()+"\t"+students[i].getEng()+"\t"
                    +students[i].getMath()+"\t"+students[i].getComp()+"\t"+students[i].getSum()+"\n";
        }
        return s;
    }
}

Next, write the main function for testing;

import java.io.*;
public class Tester {
    public static void main(String args[]){
        Student students[];
        StudentClass aClass=new StudentClass("java 0101",5);
        students=new Student[aClass.getSize()];
        for(int i=0;i<aClass.getSize();i++){
            students[i]=new Student(getAStudent(i+1));
        }
        //The setStudents method parameter of StudentClass is a variable length parameter and the incoming argument is an array
        aClass.setStudents(students);
        String sss=aClass.toString();
        System.out.println(aClass);
        //Save student information to stu.ser
        try{
            FileOutputStream fo=new FileOutputStream("stu.ser");
            ObjectOutputStream so=new ObjectOutputStream(fo);
            for(Student s:students){
                so.writeObject(s);
            }
            so.close();
        }catch (Exception e){
            System.out.println(e);
        }
    }
    public static Student getAStudent(int i){
        Student studenti;
        System.out.println("Enter #"+i+"Information for students:");
        System.out.println("School Number:");
        String id=Keyboard.getString();
        System.out.println("Full name:");
        String name=Keyboard.getString();
        System.out.println("English achievement:");
        int eng=Keyboard.getInteger();
        System.out.println("Math Scores:");
        int math=Keyboard.getInteger();
        System.out.println("Computer results:");
        int comp=Keyboard.getInteger();
        studenti=new Student(id,name,eng,math,comp);
        return studenti;
    }
}
Input and output results://Omit input before

Class: java 0101	Capacity 40	Actual number of people:5

School Number	Full name	English	Mathematics	Computer	Total results
01	Li Hong	88	76	60	224
02	Li Si	78	67	80	225
03	Zhang San	86	80	75	241
04	wheat	70	68	75	213
05	What is	80	90	78	248

Add, delete, check, change arrays

Add common methods to the StudentClass class;

lookup

Sequential search, also known as exhaustion; The basic idea is to start with the first item and compare the stored data with the data you are looking for until you find the data or find all the elements without finding the data.

//Sequential Search
    public int find(String id){
        for (int i=0;i<size;i++){
            if(students[i].getId().equals(id))
                return i;
        }
        return -1;
    }

increase

Add a student object to the end of the array.

//Add a student
    public boolean add(Student aStudent){
        if(size==capacity) return false;//No space to add
        if(find(aStudent.getId())>=0) return false;//This number already exists and cannot be added
        //Add Operation
        this.students[size]=new Student(new String(aStudent.getId()),new String(aStudent.getName()),aStudent.getEng(),aStudent.getMath(),aStudent.getComp());
        size++;
        return true;
    }

delete

//Delete a student
    public boolean del(Student aStudent){
        int pos=find(aStudent.getId());
        if(pos==-1){
            return false;//This number does not exist and cannot be deleted
        }
        //Remove this student from the array
        //Array element students[pos+1]..students[size-1] moves one position forward in turn
        //And the value of size increases by 1
        for (int i=pos+1;i<size;i++){
            students[i-1]=students[i];
        }
        size--;
        return true;
    }
    //Delete a student with a known number
    public boolean del(String id){
        int pos=find(id);
        if(pos==-1){
            return false;//This number does not exist and cannot be deleted
        }
        //Remove this student from the array
        //Array element students[pos+1]..students[size-1] moves one position forward in turn
        //And the value of size minus 1
        for (int i=pos+1;i<size;i++){
            students[i-1]=students[i];
        }
        size--;
        return true;
    }

Test Code

Tester2.java
Write a test class below to test the new find, add, and delete methods.

import java.io.*;
public class Tester2 {
    public static void main(String args[]){
        Student students[]=new Student[5];
        //From file stu.ser reads student information
        try{
            FileInputStream fi=new FileInputStream("stu.ser");
            ObjectInputStream si=new ObjectInputStream(fi);
            for(int i=0;i<5;i++){
                students[i]=(Student) si.readObject();
            }
            si.close();
        }catch (Exception e){
            System.out.println(e);
        }

        StudentClass aClass=new StudentClass("java0101",5);
        aClass.setStudents(students);
        System.out.println(aClass);
        //lookup
        for(int i=0;i<2;i++){
            System.out.print("Enter the number you want to find:");
            String id=Keyboard.getString();
            if(aClass.find(id)<0){
                System.out.println("Non-existent!");
            }else{
                System.out.println("Exists!");
            }
        }
        //increase
        for (int i=0;i<2;i++){
            Student aStudent=getAStudent(6+i);
            if(aClass.add(aStudent)){
                System.out.println("Increase success!");
            }else{
                System.out.println("No increase!");
            }
        }
        //delete
        for (int i=0;i<2;i++){
            System.out.print("Enter the number to delete");
            String id=Keyboard.getString();
            if(aClass.del(id)){
                System.out.println("Deleted!");
            }else{
                System.out.println("Non-existent!");
            }
        }
        System.out.println(aClass);
    }
    public static Student getAStudent(int i){
        Student studenti;
        System.out.println("Enter #"+i+"Information for students:");
        System.out.print("School Number:");
        String id=Keyboard.getString();
        System.out.print("Full name:");
        String name=Keyboard.getString();
        System.out.print("English achievement:");
        int eng =Keyboard.getInteger();
        System.out.print("Math Scores:");
        int math =Keyboard.getInteger();
        System.out.print("Computer results:");
        int comp =Keyboard.getInteger();
        studenti=new Student(id,name,eng,math,comp);
        return studenti;
    }
}
Class: java0101	Capacity 40	Actual number of people:5

School Number	Full name	English	Mathematics	Computer	Total results
01	Li Hong	88	76	60	224
02	Li Si	78	67	80	225
03	Zhang San	86	80	75	241
04	wheat	70	68	75	213
05	What is	80	90	78	248

Enter the number you want to find: 02
 Exists!
Enter the number you want to find: 06
 Non-existent!
Enter the information for the sixth student:
School Number: 06
 Name: Mazi
 English achievement: 78
 Math score: 90
 Computer Score: 60
 Increase success!
Enter the information for the 7th student:
School Number: 07
 Name: Xiao Liang
 English achievement: 56
 Math score: 95
 Computer Score: 89
 Increase success!
Enter the number 03 to delete
 Deleted!
Enter the number 04 to delete
 Deleted!
Class: java0101	Capacity 40	Actual number of people:5

School Number	Full name	English	Mathematics	Computer	Total results
01	Li Hong	88	76	60	224
02	Li Si	78	67	80	225
05	What is	80	90	78	248
06	Hemp seeds	78	90	60	228
07	Xiao Liang	56	95	89	240

Process finished with exit code 0

In addition, you can try to write your own.

Sort array elements

Select Sort

The basic idea of selecting sort is to select the smallest element in the unsorted sequence as the sorted subsequence first, then repeatedly select the smallest element from the unsorted subsequence, add it to the sorted sequence as the last element in the sorted subsequence until the elements in the unsorted subsequence have been processed.

//Select Sorting Algorithm
    public void selectionSort(){
        Student temp;
        for(int i=0;i<size-1;i++){
            for(int j=i+1;j<size;j++){
                if(students[j].compare(students[i])>0){
                    temp=students[i];
                    students[i]=students[j];
                    students[j]=temp;
                }
            }
        }
    }

Test class code;

import java.io.*;
public class SortTester {
    public static void main(String args[]){
        Student students[]=new Student[5];
        //From file stu.ser reads student information
        try{
            FileInputStream fi=new FileInputStream("stu.ser");
            ObjectInputStream si=new ObjectInputStream(fi);
            for(int i=0;i<5;i++){
                students[i]=(Student) si.readObject();
            }
            si.close();
        }catch (Exception e){
            System.out.println(e);
        }
        StudentClass aClass=new StudentClass("java0101",5);
        aClass.setStudents(students);
        System.out.println(aClass);
        //Select Sort
        aClass.selectionSort();
        System.out.println("Select the sorted results:\n");
        System.out.println(aClass);
    }
}
Class: java0101	Capacity 40	Actual number of people:5

School Number	Full name	English	Mathematics	Computer	Total results
01	Li Hong	88	76	60	224
02	Li Si	78	67	80	225
03	Zhang San	86	80	75	241
04	wheat	70	68	75	213
05	What is	80	90	78	248

Select the sorted results:

Class: java0101	Capacity 40	Actual number of people:5

School Number	Full name	English	Mathematics	Computer	Total results
05	What is	80	90	78	248
03	Zhang San	86	80	75	241
02	Li Si	78	67	80	225
01	Li Hong	88	76	60	224
04	wheat	70	68	75	213

Insert Sort

Insert Sorting inserts the data to be sorted one by one into the proper position in the sorted sequence according to a certain rule until all the data is inserted. Different insertion rules result in different insertion sorting algorithms. The simplest algorithm is the direct insert sort algorithm.

The direct insertion sort method first uses the first element of the unsorted element as the sorted subsequence, then from the original second element, inserts each element one by one into the appropriate position in the sorted subsequence until all elements are inserted.

//Insert sort algorithm
public void insertSort(){
    Student temp;
    for(int i=1;i<size;i++){
        temp=students[i];
        int j=i-1;
        while(j>-1 && temp.compare(students[j])>0){
            students[j+1]=students[j];
            j--;
        }
        students[j+1]=temp;
    }
}

The test code can be written with reference to the Select Sort test code.

Search algorithm

As we have seen earlier, sequential lookup algorithms are very simple, but they are inefficient to find in large amounts of data. Searching in an unsorted array can only be done using the sequential search method. For sorted arrays, we can use binary search to improve the search efficiency.

public class SortedIntArray {
    private int capacity;
    private Integer[] rep;
    private int size;
    //Construction method
    public SortedIntArray(int n){
        capacity=n;
        rep=new Integer[capacity];
    }
    //Construction method without parameters
    public SortedIntArray(){
        this(100);
    }
    //Binary Search
    private int search(int i, int lower, int upper){
        int index=lower;
        if(upper>=lower){
            int mid=(upper+lower)/2;
            int cur=rep[mid].intValue();
            if(cur==i){
                index=mid;
            }else if(cur<i){
                index=search(i,mid+1,upper);
            }else{
                index=search(i,lower,mid-1);
            }
        }
        return index;
    }
    public int search(int i){
        return search(i,0,size-1);
    }
    //Insert an element into the array
    public SortedIntArray insert(int i){
        int index=search(i);
        for (int j=size;j>index;--j){
            rep[j]=rep[j-1];
        }
        rep[index]=i;
        ++size;
        return this;
    }
    //Delete an element from the array. Delete only the first element found
    public SortedIntArray remove(int i){
        int index=search(i);
        if(rep[index]==i){
            --size;
            for(int j=index;j<size;++j){
                rep[j]=rep[j+1];
            }
        }
        return this;
    }
    @Override
    public String toString(){
        String toReturn="";
        for(int i=0;i<size;++i){
            toReturn+=rep[i].toString()+", ";
        }
        return toReturn;
    }
    //Main method
    static public void main(String[] args){
        SortedIntArray anArray=new SortedIntArray();
        anArray.insert(4).insert(9).insert(7).insert(1).insert(3).insert(2).insert(8).insert(7);
        System.out.println(anArray);
        anArray.remove(1).remove(8).remove(7).remove(3);
        System.out.println(anArray);
    }
}
Output results:
1, 2, 3, 4, 7, 7, 8, 9, 
2, 4, 7, 9, 

2-D Array

Two-dimensional arrays are often used to represent two-dimensional tables, that is, to represent data in rows and columns.

Declarations for two-dimensional arrays;

type arrayName[][];
type [][] arrayName;
public class TableTester {
    public static void main(String args[]){
        int myTable[][]={{23,45,66,34,21,67,79},
                {45,15,19,46,98,63,88},
                {98,82,65,90,20,15,25},
                {55,44,55,77,22,44,33}
        };
        //Display a two-dimensional table using an enhanced for loop;
        for(int row[]:myTable){
            for(int col:row){
                System.out.print(col+" ");
            }
            System.out.println();
        }
        //Calculate additive and maximum line numbers
        int sum,max,maxRow=0;
        max=0;
        for(int row=0;row<4;row++){
            sum=0;
            for(int col=0;col<7;col++){
                sum+=myTable[row][col];
            }
            if(sum>max){
                max=sum;
                maxRow=row;
            }
        }
        System.out.println("Row "+maxRow+" has the highest sum of "+max);
    }
}
Output results;
23 45 66 34 21 67 79 
45 15 19 46 98 63 88 
98 82 65 90 20 15 25 
55 44 55 77 22 44 33 
Row 2 has the highest sum of 395

Topics: Java Algorithm array