如何从类型中删除Arraylist中的元素

时间:2017-01-18 17:10:25

标签: java iterator

说,我有一个ArrayList:

List<Transaction> txList 

我还有几个扩展基类的事务 - 事务:

public class ATransaction extends Transaction {...}
public class BTransaction extends Transaction {...}
public class CTransaction extends Transaction {...}
... 10-12 more different kind of Transactions extends Transaction class

在代码的某些部分,我将删除这些交易。

for (Object tx : transactions) {
    if (tx instanceof ATransaction) {
        CustomerSession.remove((ATransaction) t);
    } else if (tx instanceof BTransaction) {
        CustomerSession.remove((BTransaction) t);
    } else if ...
}

CustomerSession:
    public void remove(Transaction t) {
        Iterator itr = txList.iterator();

        while (itr.hasNext()) {
           //How to compare the type of iterator with that of the argument "t" passed in the remove method and do an - iterator remove - below when the condition is met
              itr.remove();
        }
    }

谢谢!

3 个答案:

答案 0 :(得分:3)

如果你不知道这些类型,也许这个带有泛型的选项会更合适。 remove方法如下所示:

public void remove(Class<? extends Transaction> cls) {
    Iterator itr = transactions.iterator();

    while (itr.hasNext()) {
        if (itr.next().getClass().equals(cls)) {
            System.out.println("removing");
            itr.remove();
        }
    }
}

签名Class<? extends Transaction> cls将确保您需要将类作为扩展Transaction的参数传递,并像ATransaction一样。

找到以下代码:

public class ListStuff {

List<Transaction> transactions = new ArrayList<>();

public ListStuff() {
    //Add some data
    transactions.add(new ATransaction());
    transactions.add(new DTransaction());
    transactions.add(new ATransaction());
    transactions.add(new ATransaction());
    transactions.add(new CTransaction());
    transactions.add(new ATransaction());
    transactions.add(new BTransaction());
    transactions.add(new CTransaction());
    transactions.add(new BTransaction());
    transactions.add(new BTransaction());
    transactions.add(new CTransaction());
    transactions.add(new CTransaction());
    transactions.add(new DTransaction());

    remove(ATransaction.class); //This will remove all ATrasaction from the list
    remove(BTransaction.class); // This will remove all BTransaction from the list
    transactions.stream().forEach(System.out::println);
}


public void remove(Class<? extends Transaction> cls) {
    Iterator itr = transactions.iterator();

    while (itr.hasNext()) {
        if (itr.next().getClass().equals(cls)) {
            System.out.println("removing");
            itr.remove();
        }
    }
}


public abstract class  Transaction {


}


public class ATransaction extends Transaction{

    @Override
    public String toString() {
        return "A";
    }

}

public class BTransaction extends Transaction{
    @Override
    public String toString() {
        return "B";
    }
}

public class CTransaction extends Transaction{
    @Override
    public String toString() {
        return "C";
    }
}

public class DTransaction extends Transaction{
    @Override
    public String toString() {
        return "D";
    }
}
}

答案 1 :(得分:2)

您也可以使用迭代器:

fit$where[fit$where==3] # for Node 3
#  Hornet 4 Drive   Hornet Sportabout             Valiant          Duster 360           Merc 240D            Merc 280           Merc 280C 
#              3                   3                   3                   3                   3                   3                   3 
#     Merc 450SE          Merc 450SL         Merc 450SLC  Cadillac Fleetwood Lincoln Continental   Chrysler Imperial    Dodge Challenger 
#              3                   3                   3                   3                   3                   3                   3 
#    AMC Javelin          Camaro Z28    Pontiac Firebird 
              3                   3                   3 
length(fit$where[fit$where==3])
#[1] 17

mtcars[rownames(mtcars) %in% names(fit$where[fit$where==3]),]
#                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb  x
#Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1  4
#Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2  5
#Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1  6
#Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4  7
#Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2  8
#Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4 10
#Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4 11
#Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3 12
#Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3 13
#Merc 450SLC         15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3 14
#Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4 15
#Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4 16
#Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4 17
#Dodge Challenger    15.5   8 318.0 150 2.76 3.520 16.87  0  0    3    2 22
#AMC Javelin         15.2   8 304.0 150 3.15 3.435 17.30  0  0    3    2 23
#Camaro Z28          13.3   8 350.0 245 3.73 3.840 15.41  0  0    3    4 24
#Pontiac Firebird    19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2 25

修改

如果要组织过滤类,请创建一个地图并设置为true(如果存在)。

首先创建常量:

    Iterator<Transaction> iterator = transactions.iterator();
    while(iterator.hasNext()) {
        Transaction tx = iterator.next();
        if (tx instanceof ATransaction) {
            iterator.remove();
        } else if (tx instanceof BTransaction) {
            iterator.remove();
        }
    }

更新你的课程,创建一个中产阶级:

Constants.ATransaction = "ATransaction ";
Constants.BTransaction = "BTransaction ";
...

在构建时使用所需的地图填充地图:

public class MyTransaction extends Transaction {
    public String baseClassName;
    MyTransaction (String baseClassName) {
        super();
        baseClassName = baseClassName;
    }
}

public class ATransaction extends MyTransaction {
    ATransaction() {
        super(Constants.ATransaction);
    }
}
...

然后在迭代时检查它们:

Map<String, Boolean> transactionClasses = new HashMap<>();
transactionClasses.put(Constants.ATransaction, true);
transactionClasses.put(Constants.BTransaction, true);
...

答案 2 :(得分:0)

根据Determine if two Java objects are of the same class中接受的答案,答案取决于您是否寻求与t完全相同的类或其派生类。

public void remove(Transaction t) {
    Iterator itr = txList.iterator();

    while (itr.hasNext()) {
          //if(itr.next().getClass().equals( t.getClass())  /*if the current element should be of the exact same type as t */
          if(itr.next().getClass().isAssignableTo(t.getClass()))  /*if the current element is allowed to be a child element of t*/
              itr.remove();
    }
}

另请注意,在代码的第一部分中,最好使用增强型for语句中的父Transaction类而不是Object,因为它会增强类型安全性,并且您可以从列表中删除时,不必向下转换为子类型(例如,'ATransaction'):

for (Transaction tx : transactions) {
  if (tx instanceof ATransaction) {
      CustomerSession.remove(t);
  } else if (tx instanceof BTransaction) {
      CustomerSession.remove(t);
  } else if ...
}

甚至可以用一些||而不是嵌套的if-else

来做一切