ArrayList知识点整理

版权声明:本文为博主原创,未经允许请不要转载哦 https://blog.csdn.net/weixin_43277507/article/details/88738640

ArrayList的遍历
ArrayList主要有三种遍历方式,for循环遍历、for each遍历、iterator遍历,仍旧以以Car为例,具体遍历方法如下:

public class Car {
   String CarID;
   int maxVelocity;
   
   public boolean equals(Car car) {
		if(this.CarID.equals(car.getCarID())) return true;
		else return false;
	}
   
   public Car(String string, int i) {
	  CarID=string;
	  maxVelocity=i;
   }
   public String getCarID() {
	  return CarID;
   }
   public void setCarID(String carID) {
	  CarID = carID;
   }
   public int getMaxVelocity() {
	  return maxVelocity;
   }
   public void setMaxVelocity(int maxVelocity) {
	  this.maxVelocity = maxVelocity;
   }
   
}

public class Solution{
    public static void main(String [] args){
       LinkedList<Car> cars = new LinkedList<Car>();
       Car car1=new Car("01",20);
       Car car2=new Car("02",10);
       Car car3=new Car("03",30);
       //Car car4=new Car("01",20);
       cars.add(car1);
       cars.add(car2);
       cars.add(car3);
       //cars.add(car4);
       /**
       * 不同的遍历方式
       */
       }
   }

1、for循环遍历

       for(int i=0;i<cars.size();i++) {
    	   System.out.println(cars.get(i).getCarID()+'\t' + cars.get(i).getMaxVelocity());
       }

2、for each遍历

       for(Car car:cars) {
    	   System.out.println(car.CarID + '\t' + car.maxVelocity);
       }

3、iterator遍历

       Iterator it =cars.iterator();
       while(it.hasNext()) {
    	   Car car = (Car)it.next();
    	   System.out.println(car.CarID+'\t'+car.maxVelocity);
       }

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88738640