【问题标题】:Index the ID number in an ArrayList索引 ArrayList 中的 ID 号
【发布时间】:2016-04-21 20:08:19
【问题描述】:

所以,我有一个取自 .txt 文件的 ArrayList。它显示以下详细信息:

Id
Car Manufacturer
Car Type
Colour
*blank line*

例如:

21
Vauxhall
Corsa
red

19
Vauxhall
Corsa
blue

18
Vauxhall
Corsa
White

我很好奇如何使Id成为ArrayList的“索引”,这样如果汽车被删除或添加到Arraylist,它会自动调整Id编号。

【问题讨论】:

  • 也许使用HashMap 代替...
  • Arraylists 不允许任意的、非连续的索引。 Map 有点味道会更好。
  • 这感觉就像XY problem。你这样做是为了达到什么目的?
  • Stack records = new Stack(); - 不要使用原始类型:Stack<Album> records = new Stack<>();。另外,我认为您的意思可能是\n,而不是/n
  • 这取决于你的ID字段的范围,如果第一个是1,而第二个是99999,这对数组不利。所以你可以尝试使用MapHashTable

标签: java arraylist


【解决方案1】:

您需要将 ID 设置为该 ArrayList 的主键。您可以通过创建一个包含 HashMap 对象的 ArrayList 来做到这一点

ArrayList<HashMap<int, CarObject>> = new ArrayList()

然后排序变成了遍历 ArrayList 对象中的整数 ID 的问题

【讨论】:

    【解决方案2】:

    您使用了错误的 DataStructure... 对于您的目的,HashMap 或 LinkedHashMap 之类的东西会更理想。你可以把你所有的汽车数据放在pojos中

    class Car {
    int Id;
    String make, style, color; 
    getters/setters....; 
    }
    List<Car> list = myReadMethod();
    
    //Then you make 
    Map<int, Car> myCars = new HashMap<Int, Car>;
    for(Car car : list)
         myCars.put(car.getId, car);  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 2012-11-27
      相关资源
      最近更新 更多