自定义类数组创建和初始化 Java怎样自定义类数组的创建和初始化

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

自定义类数组创建和初始化 Java怎样自定义类数组的创建和初始化

Keplery_   2021-10-27 我要评论
想了解Java怎样自定义类数组的创建和初始化的相关内容吗,Keplery_在本文为您仔细讲解自定义类数组创建和初始化的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java自定义类数组,自定义类数组创建,自定义类数组初始化,下面大家一起来学习吧。

自定义类数组的创建和初始化

刚刚在慕课学习Java的集合类List过程中,向集合中添加元素时,遇到一个问题:

定义了一个Course类

public class Course {
    private String id;    
    private String name;  //课程名称
    //get  set方法
    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;
    }

在测试类中有一个Course类的List集合allCourses,一个向该List集合添加元素的方法addToAllCourses() ;

public class ListTest {  
    private List allCourses;  //用于存放备选课程的List
    //构造函数,初始化allCourses
    public ListTest() {         
        this.allCourses = new ArrayList();
    }
    public void addToAllCourses(String id, String name) {
        //List的add(Object e), 添加一个元素
        Course cs = new Course();  //创建一个Course对象,并设置其参数
        cs.setId(id);   
        cs.setName(name);
        allCourses.add(cs); 
        // List的addAll(Collection c)方法      
        Course[] courses = new Course[3];
        courses[0].setId("2");
        courses[0].setName("C语言");
        courses[1].setId("3");
        courses[1].setName("数据库");
        courses[2].setId("4");
        courses[2].setName("计算机网络");
        allCourses.addAll(Arrays.asList(courses));  
        //在该方法中 参数必须为collection类型,因此必须用工具类进行类型转换
     }  
}

主函数测试

    public static void main(String[] args) {
        ListTest list = new ListTest();
        list.addToAllCourses("1", "数据结构");
        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());
        }
    }

乍看是没有问题的,但是一运行,问题就来了,myeclipse报出了空指针异常。异常抛出点为addToAllCourses()方法中 Course类数组courses在赋值时的代码。

  

既然是空指针异常,也就是说,courses[0], courses[1], courses[2]都是没有被初始化的。

  

一般而言,如下的数组定义在myeclipse中是不会报错的:

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

但是,我的代码中,数组的类型为自定义的类,而非Java本身提供的类(如String类),因而我怀疑是不是我的数组定义出了问题. 查阅资料后发现,自定义类的数组定义后的初始化应该如下:

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

也就是说,在声明了自定义类的数组之后,对每一个数组元素的初始化,都要为其new一个对象出来使得指针指向该对象,Java语言本身是不提供在自定义类数组声明时候自动创建新对象的方式的。

  

此处顺便再补充一下类二维数组的定义及初始化,

/*Java提供类*/
        //方式一:
        String[][] s = new String[][] { {"a", "b", "c"},
                                        {"d", "e", "f"}  };
        //方式二
        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++);
            }
/*自定义类*/
        Course[][] courses = new Course[2][3];  //声明
        courses[0][0] = new Course();  //使用时new一个实例
        courses[0][0].setId("0");
        courses[0][0].setName("000000");
        System.out.println(courses[0][0].getId() + "  " 
                           + courses[0][0].getName());
        //测试 不报空指针异常

自定义类封装数组,添加类方法实现数据

1、具体见注释

2、后续或有更新

public class MyArray {
    private long[] array;
    private int cnt; // 自定义数组类的元素个数
    /**
    使用自定义类封装数组,添加类方法实现数据操作
    */
    public MyArray() {
        array = new long[50];
    }
    public MyArray(int size) {
        array = new long[size];
    }
    /**
    插入数据,返回值为空
    */
    public void insert(long insertValue) {
        array[cnt++] = insertValue;
    }
    /**
    显示数据,返回值为空
    */
    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("]");
    }
    /**
    按值查找数据,返回索引值
    算法:线性查找
    */
    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; // 保持单一出口
    }
    /**
    按索引查找数据,返回值为目标数据
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
    按值删除数据,返回其索引值
    */
    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; // 仅删除从左到右第一个找到的目标值
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; // 保持单一出口
    }
    /**
    按索引删除数据,返回值为空
    */
    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]; // 替换上两行
        }
    }
    /**
    根据索引值,更新数据,返回值为空
    */
    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、添加自定义有序数组类

public class MyOrderArray {
    private long[] array;
    private int cnt; // 自定义数组类的元素个数
    /**
    使用自定义类封装数组,添加类方法实现数据操作
    */
    public MyOrderArray() {
        array = new long[50];
    }
    public MyOrderArray(int size) {
        array = new long[size];
    }
    /**
    按序插入数据,返回值为空
    */
    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++;
    }
    /**
    显示数据,返回值为空
    */
    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("]");
    }
    /**
    按值查找数据,返回索引值
    算法:线性查找
    */
    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; // 保持单一出口
    }
    /**
    按索引查找数据,返回值为目标数据
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
    按值删除数据,返回其索引值
    */
    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; // 仅删除从左到右第一个找到的目标值
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; // 保持单一出口
    }
    /**
    按索引删除数据,返回值为空
    */
    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]; // 替换上两行
        }
    }
    /**
    根据索引值,更新数据,返回值为空
    */
    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类与MyOrderArray类目前仅区别于insert方法,后续或有更新

5、MyOrderArray类新增二分查找方法binarySearch,具体细节见该方法代码

public class MyOrderArray {
    private long[] array;
    private int cnt; // 自定义数组类的元素个数
    /**
    使用自定义类封装数组,添加类方法实现数据操作
    */
    public MyOrderArray() {
        array = new long[50];
    }
    public MyOrderArray(int size) {
        array = new long[size];
    }
    /**
    按序插入数据,返回值为空
    */
    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++;
    }
    /**
    显示数据,返回值为空
    */
    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("]");
    }
    /**
    按值查找数据,返回索引值
    算法:线性查找
    */
    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; // 保持单一出口
    }
    /**
    按值查找数据,返回索引值
    算法:二分查找
    */
    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; // 切记减一
            } else if (targetValue >= array[middle]) {
                low = middle + 1; // 切记加一
            }
        }
    }
    /**
    按索引查找数据,返回值为目标数据
    */
    public long get(int targetIndex) {
        if (targetIndex < 0 || targetIndex >= cnt) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            return array[targetIndex];
        }
    }
    /**
    按值删除数据,返回其索引值
    */
    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; // 仅删除从左到右第一个找到的目标值
            }
        }
        if (i == cnt) {
            deleteResult = -1;
        } else {
            deleteResult = i;
        }
        return deleteResult; // 保持单一出口
    }
    /**
    按索引删除数据,返回值为空
    */
    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]; // 替换上两行
        }
    }
    /**
    根据索引值,更新数据,返回值为空
    */
    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();
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们