如何使用String从数组列表中获取数据

时间:2014-04-22 11:30:07

标签: java arrays sorting

我在这里有一个数组列表:

 ArrayList <vehicles> carsArray = new ArrayList<vehicles>();
    carsArray.add(new vehicles ("CAR","Peugot","3008",12500.00));
    carsArray.add(new vehicles ("CAR","BMW","316",4995.00));
    carsArray.add(new vehicles ("CAR","Ford","Fiesta",12995.00));

    carsArray.add(new vehicles ("VAN","P","3008",22500.00));
    carsArray.add(new vehicles ("VAN","B","316",24995.00));
    carsArray.add(new vehicles ("VAN","F","Fiesta",22995.00));

我想要做的就是通过这个数组列表,只获得面包车。有没有办法循环通过阵列,如果车辆类型是&#34;面包车&#34;打印到控制台。

由于

5 个答案:

答案 0 :(得分:1)

vehicles类中,您应该为该String设置 getter ,然后您可以轻松检查该对象是否具有“VAN”字符串或其他内容。

class Vehicles {
  ...
  ...

   public boolean isVan() {
       return "VAN".equals(myType);
   }

}

请遵循Java命名约定并将类名更改为以大写字母开头。

答案 1 :(得分:1)

是的。 ArrayLists可以使用高级for循环,如数组。这样做:

for (vehicles vehicle : carsArray) {
    if (vehicle.getType().equals("VAN")) { //Assuming get type method exists
         System.out.println("Vehicle " + vehicle.getName() + " is a van");
    }
}

或者如果您需要索引:

for (int i = 0; i < vehicle.size(); i++) {
    if (carsArray.get(i).getType().equals("VAN")) {
        System.out.println("Vehicle at index " + i + " is a van.");
    }
}

答案 2 :(得分:1)

可能是这样的:

for(int i=0; i<carsArray.size(); i++) {
    if(carsArray.get(i).getType().equals("VAN")
        System.out.println(carsArray.get(i).getModel());
}

这假设Vehicle类看起来像:

class Vehicle {
    String type;
    String brand;
    String model;
    String speed;

    private String getType() {
        return type;
    }

    private String setType(String vehType) {
        type = vehType;
    }

    ...
}

答案 3 :(得分:0)

for (vehicles vehicles : carsArray) {
    if(vehicles.getS1().equalsIgnoreCase("Van")) {
        System.out.println(vehicles);
    }
}

答案 4 :(得分:0)

for(vehicles v:  carsArray) {
    // v is vehicle obj inside carsArray
    // you can check the desired condition here
}