本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
Java如何自定义类数组的创建和初始化
追忆似水年华 · 366浏览 · 发布于2021-10-27 +关注

这篇文章主要介绍了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,具体细节见该方法代码

                                   java
                                 

相关推荐

PHP实现部分字符隐藏

沙雕mars · 1325浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 908浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 970浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 962浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1086浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页