Java-Array&ArrayList

  • data[] a = new data[size] || data[]a = {*,* ,* ,* ,*… }(number of element = size)
    • declear and internalize a data type array named a
    • always internalize array
      • compiler error
    • data[][] a = new data[width][height] || data[][]a = {{*,*…},{* ,* …}{* ,*…}… }
      • two-dimension array
  • a.length() return capacity of a
  • copy array(data[] c = a) is share reference of data array to a and c
  • length of array is fixed
    • can be repersented by a variable to avoid usage of magic number
  • use Scanner.hasNextData and for loop to keep track number of element been internalized to Array
  • for(data x : a) traverse all element been internalized into array
  • use array iff you have a long list and known number of primitive data and can or should not convert to Wapper class

 

  • use arrayList when you are not sure about how many element you will have
  • import java.util.ArrayList package
    • a generic class(hold any data type)
  • ArrayList<data> b = new ArrayList<data>();
    • declear and internalize
  • useful functions
    • b.add(data1) add data1 to the end of b
    • b.add(n,data1) add data1 to the position n of b and the element after move 1 to the end
    • b.set(n,data1) set position n of b to data1
    • b.size() return number of element stored in b
    • b.get(n) get data stored at position n of b
    • b.remove(n) remove position n`s data, all data after go up 1
    • System.out.println(b) print all data stored in b as a string
  • ArrayList <data> d = b || ArrayList<data> d = new ArrayList<data>(b)
    • copy reference of b to d
  • lecture6arrays
  • convert from primitive type to wrapper class is auto and use auto-boxing
  • ArrayList can only use Wrapper class type not primitive type

留下评论