集合的理解和好处(Understanding and benefits of collections)

集合的理解和好处

  • 数组的不足之处:

    长度开始时必须指定,而且一旦指定,不能更改
    保存的必须为同一类型的元素
    使用数组进行增加/删除元素的示意代码-比较麻烦

  • 长度开始时必须指定,而且一旦指定,不能更改
  • 保存的必须为同一类型的元素
  • 使用数组进行增加/删除元素的示意代码-比较麻烦
  • 写出Person数组扩容示意代码。
Person[] pers = new Person[1];//大小是1
per[0] = new Person();

//**增加新的Person对象?**
Person[] pers2 = new Person[pers.length+1];//创建新数组
for(){}//拷贝pers数组的元素到pers2
pers2[pers2.length-1] = new Person();//添加新的对象  
  • 集合的好处:

    可以动态保存任意多个对象,使用比较方便!
    提供了一系列方便的操作对象的方法:add、remove、set、get等
    使用集合添加,删除新元素的示意代码-简洁了

  • 可以动态保存任意多个对象,使用比较方便!
  • 提供了一系列方便的操作对象的方法:add、remove、set、get等
  • 使用集合添加,删除新元素的示意代码-简洁了
————————

Understanding and benefits of collections

  • Disadvantages of array:
    The length must be specified at the beginning and cannot be changed once specified
    Saved elements must be of the same type
    Schematic code for adding / deleting elements using arrays – more troublesome
  • The length must be specified at the beginning and cannot be changed once specified
  • Saved elements must be of the same type
  • Schematic code for adding / deleting elements using arrays – more troublesome
  • Write the schematic code for expanding the capacity of the person array.
Person[] pers = new Person[1];//大小是1
per[0] = new Person();

//**增加新的Person对象?**
Person[] pers2 = new Person[pers.length+1];//创建新数组
for(){}//拷贝pers数组的元素到pers2
pers2[pers2.length-1] = new Person();//添加新的对象  
  • Collection benefits:
    You can dynamically save any number of objects, which is more convenient to use!
    It provides a series of convenient methods to manipulate objects: add, remove, set, get, etc
    Use the collection to add and delete the schematic code of new elements – concise
  • You can dynamically save any number of objects, which is more convenient to use!
  • It provides a series of convenient methods to manipulate objects: add, remove, set, get, etc
  • Use the collection to add and delete the schematic code of new elements – concise