Java How to Customize the Creation and Initialization of Class Arrays

  • 2021-12-04 18:41:29
  • OfStack

Creation and Initialization of Directory Custom Class Array Custom class encapsulates array and adds class method implementation data

Creation and initialization of custom class array

Just in the process of learning Java's collection class List in massive open online course, I encountered a problem when adding elements to the collection:

1 Course class is defined


public class Course {
    private String id;    
    private String name;  // Course name 
    //get  set Method 
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

In the test class, there is an List set of Course class allCourses, and a method addToAllCourses () that adds elements to the List set;


public class ListTest {  
    private List allCourses;  // Used to store alternative courses List
    // Constructor that initializes the allCourses
    public ListTest() {         
        this.allCourses = new ArrayList();
    }
    public void addToAllCourses(String id, String name) {
        //List Adj. add ( Object e ) ,  Add 1 Elements 
        Course cs = new Course();  // Create 1 A Course Object and set its parameters 
        cs.setId(id);   
        cs.setName(name);
        allCourses.add(cs); 
        // List Adj. addAll ( Collection c ) Method       
        Course[] courses = new Course[3];
        courses[0].setId("2");
        courses[0].setName("C Language ");
        courses[1].setId("3");
        courses[1].setName(" Database ");
        courses[2].setId("4");
        courses[2].setName(" Computer network ");
        allCourses.addAll(Arrays.asList(courses));  
        // In this method   Parameter must be collection Type, you must use tool classes for type conversion 
     }  
}

Main function test


    public static void main(String[] args) {
        ListTest list = new ListTest();
        list.addToAllCourses("1", " Data structure ");
        List<Course> li = list.getAllCourses();
        for(int i = 0; i < li.size(); i++) {
            System.out.println((i + 1) + ": " + li.get(i).getId() 
                               + " " + li.get(i).getName());
        }
    }

At first glance, there is no problem, but when 1 runs, the problem comes, and myeclipse reports a null pointer exception. The exception throw point is the code of the Course class array courses in the addToAllCourses () method at the time of assignment.

  

Since it is a null pointer exception, that is, courses [0], courses [1], courses [2] are not initialized.

  

1 In general, the following array definitions are error-free in myeclipse:


String[] s = new String[3];
s[0] = "000000";
System.out.println(s[0]);

However, in my code, the type of array is a custom class, not a class provided by Java itself (such as String class), so I wonder if there is something wrong with my array definition. After looking up the data, it is found that the initialization of the array definition of the custom class should be as follows:


        Course[] courses = new Course[3];
        courses[0] = new Course();
        courses[0].setName("0000000");
        System.out.println(courses[0].getName());

That is to say, after declaring the array of custom classes, the initialization of every array element should come out for its new1 objects so that the pointer points to the object. Java language itself does not provide a way to automatically create new objects when declaring the array of custom classes.

  

Here, by the way, the definition and initialization of class 2-dimensional array under 1 are added.


/*Java Provision class */
        // Mode 1:
        String[][] s = new String[][] { {"a", "b", "c"},
                                        {"d", "e", "f"}  };
        // Mode 2
        int r = 0;
        String[][] s = new String[2][3];
        for (int i = 0; i < 2; i++) 
            for (int j = 0; j < 3; j++) {
                s[i][j] = String.valueOf(r++);
            }
/* Custom class */
        Course[][] courses = new Course[2][3];  // Declaration 
        courses[0][0] = new Course();  // When in use new1 Instances 
        courses[0][0].setId("0");
        courses[0][0].setName("000000");
        System.out.println(courses[0][0].getId() + "  " 
                           + courses[0][0].getName());
        // Test   Do not report null pointer exceptions 

Custom class encapsulation array, add class method implementation data

1. See the notes for details

2. Subsequent updates or updates


public class MyArray {
    private long[] array;
    private int cnt; //  Number of elements of a custom array class 
    /**
     Use custom classes to encapsulate arrays and add class methods to implement data operations 
    */
    public MyArray() {
        array = new long[50];
    }
    public MyArray(int size) {
        array = new long[size];
    }
    /**
     Insert data and return value is null 
    */
    public void insert(long insertValue) {
        array[cnt++] = insertValue;
    }
    /**
     Display data with null return value 
    */
    public void display() {
        System.out.print("[");
        for (int i = 0; i < cnt ; ++i) {
            System.out.print(array[i]);
            if (i != cnt - 1) {
                System.out.print(",");
            }
        }
        System.out.println("]");
    }
    /**
     Find data by value and return index value 
     Algorithm: Linear lookup 
    */
    public int search(long targetValue) {
        int i;
        int searchResult;
        for (i = 0; i < cnt; ++i) {
            if (targetValue == array[i]) {
                break;
            }
        }
        if (i == cnt) {
            searchResult = -1;
        } else {
            searchResult = i;
        }
        return searchResult; //  Retention sheet 1 Export 
    }
    /**
     Find data by index, and the return value is the target data 
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
     Delete data by value and return its index value 
    */
    public int deleteByValue(long deleteValue) {
        int i;
        int deleteResult;
        for (i = 0; i < cnt; ++i) {
            if (array[i] == deleteValue) {
                int j;
                for (j = i; j < cnt-1; ++j) {
                    array[j] = array[j+1];
                }
                array[j] = array[--cnt];
                break; //  Delete only left-to-right columns 1 Target values found 
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; //  Retention sheet 1 Export 
    }
    /**
     Delete data by index, return value is null 
    */
    public void delete(int index) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            int i;
            for (i = index; i < cnt - 1; ++i) {
                array[i] = array[i + 1];
            }
            //array[i] = array[cnt - 1];
            //cnt--;
            array[i] = array[--cnt]; //  Replace the last two lines 
        }
    }
    /**
     According to the index value, update the data, and the return value is empty 
    */
    public void update(int index, int newValue) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            array[index] = newValue;
        }
    }
    public static void main(String[] args) {
        MyArray array = new MyArray(3);
        array.insert(13);
        array.insert(34);
        array.insert(90);
        array.display();
        array.deleteByValue(34);
        array.display();
    }
}

3. Add a custom ordered array class


public class MyOrderArray {
    private long[] array;
    private int cnt; //  Number of elements of a custom array class 
    /**
     Use custom classes to encapsulate arrays and add class methods to implement data operations 
    */
    public MyOrderArray() {
        array = new long[50];
    }
    public MyOrderArray(int size) {
        array = new long[size];
    }
    /**
     Insert data in order, and the return value is null 
    */
    public void insert(long insertValue) {
        int i;
        for (i = 0; i < cnt; ++i) {
            if (array[i] > insertValue) {
                break;
            }
        }
        int j;
        for (j = cnt; j > i; --j) {
            array[j] = array[j - 1];
        }
        array[i] = insertValue;
        cnt++;
    }
    /**
     Display data with null return value 
    */
    public void display() {
        System.out.print("[");
        for (int i = 0; i < cnt ; ++i) {
            System.out.print(array[i]);
            if (i != cnt - 1) {
                System.out.print(",");
            }
        }
        System.out.println("]");
    }
    /**
     Find data by value and return index value 
     Algorithm: Linear lookup 
    */
    public int search(long targetValue) {
        int i;
        int searchResult;
        for (i = 0; i < cnt; ++i) {
            if (targetValue == array[i]) {
                break;
            }
        }
        if (i == cnt) {
            searchResult = -1;
        } else {
            searchResult = i;
        }
        return searchResult; //  Retention sheet 1 Export 
    }
    /**
     Find data by index, and the return value is the target data 
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
     Delete data by value and return its index value 
    */
    public int deleteByValue(long deleteValue) {
        int i;
        int deleteResult;
        for (i = 0; i < cnt; ++i) {
            if (array[i] == deleteValue) {
                int j;
                for (j = i; j < cnt-1; ++j) {
                    array[j] = array[j+1];
                }
                array[j] = array[--cnt];
                break; //  Delete only left-to-right columns 1 Target values found 
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; //  Retention sheet 1 Export 
    }
    /**
     Delete data by index, return value is null 
    */
    public void delete(int index) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            int i;
            for (i = index; i < cnt - 1; ++i) {
                array[i] = array[i + 1];
            }
            //array[i] = array[cnt - 1];
            //cnt--;
            array[i] = array[--cnt]; //  Replace the last two lines 
        }
    }
    /**
     According to the index value, update the data, and the return value is empty 
    */
    public void update(int index, int newValue) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            array[index] = newValue;
        }
    }
    public static void main(String[] args) {
        MyOrderArray array = new MyOrderArray(3);
        array.insert(90);
        array.insert(13);
        array.insert(34);
        array.display();
        array.deleteByValue(34);
        array.display();
    }
}

4. MyArray class and MyOrderArray class are only different from insert method at present, and may be updated later

5. A 2-point search method binarySearch is added to MyOrderArray class. See the method code for details


public class MyOrderArray {
    private long[] array;
    private int cnt; //  Number of elements of a custom array class 
    /**
     Use custom classes to encapsulate arrays and add class methods to implement data operations 
    */
    public MyOrderArray() {
        array = new long[50];
    }
    public MyOrderArray(int size) {
        array = new long[size];
    }
    /**
     Insert data in order, and the return value is null 
    */
    public void insert(long insertValue) {
        int i;
        for (i = 0; i < cnt; ++i) {
            if (array[i] > insertValue) {
                break;
            }
        }
        int j;
        for (j = cnt; j > i; --j) {
            array[j] = array[j - 1];
        }
        array[i] = insertValue;
        cnt++;
    }
    /**
     Display data with null return value 
    */
    public void display() {
        System.out.print("[");
        for (int i = 0; i < cnt ; ++i) {
            System.out.print(array[i]);
            if (i != cnt - 1) {
                System.out.print(",");
            }
        }
        System.out.println("]");
    }
    /**
     Find data by value and return index value 
     Algorithm: Linear lookup 
    */
    public int search(long targetValue) {
        int i;
        int searchResult;
        for (i = 0; i < cnt; ++i) {
            if (targetValue == array[i]) {
                break;
            }
        }
        if (i == cnt) {
            searchResult = -1;
        } else {
            searchResult = i;
        }
        return searchResult; //  Retention sheet 1 Export 
    }
    /**
     Find data by value and return index value 
     Algorithm: 2 Separate search 
    */
    public int binarySearch(long targetValue) {
        int middle = 0;
        int low = 0;
        int top = cnt;
        while (true) {
            middle = (top + low) / 2;
            if (targetValue == array[middle]) {
                return middle;
            } else if (low > top) {
                return -1;
            } else if (targetValue < array[middle]) {
                top = middle - 1; //  Remember to subtract 1
            } else if (targetValue >= array[middle]) {
                low = middle + 1; //  Remember to add 1
            }
        }
    }
    /**
     Find data by index, and the return value is the target data 
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
     Delete data by value and return its index value 
    */
    public int deleteByValue(long deleteValue) {
        int i;
        int deleteResult;
        for (i = 0; i < cnt; ++i) {
            if (array[i] == deleteValue) {
                int j;
                for (j = i; j < cnt-1; ++j) {
                    array[j] = array[j+1];
                }
                array[j] = array[--cnt];
                break; //  Delete only left-to-right columns 1 Target values found 
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; //  Retention sheet 1 Export 
    }
    /**
     Delete data by index, return value is null 
    */
    public void delete(int index) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            int i;
            for (i = index; i < cnt - 1; ++i) {
                array[i] = array[i + 1];
            }
            //array[i] = array[cnt - 1];
            //cnt--;
            array[i] = array[--cnt]; //  Replace the last two lines 
        }
    }
    /**
     According to the index value, update the data, and the return value is empty 
    */
    public void update(int index, int newValue) {
        if (index < 0 || index >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            array[index] = newValue;
        }
    }
    public static void main(String[] args) {
        MyOrderArray array = new MyOrderArray(3);
        array.insert(90);
        array.insert(13);
        array.insert(34);
        array.display();
        //array.deleteByValue(34);
        System.out.println(array.binarySearch(90));
        array.display();
    }
}

Related articles: