如何删除ArrayList Android

时间:2015-10-14 16:54:57

标签: java android arraylist

我想删除在ArrayList列表中有副本的项目。

例如:

列表= {54,55,55} NewList = {54}

OR

列表= {54,55,55,55} NewList = {54,55}

我的代码:

public void submit(){
        checked.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                int j = 0;
                int k = 1;
                int l =0;
                int size = list.size();
                String temp = "";

                //removing common
                while (j < size) {
                    while(k < size){
                        if(list.get(j) == list.get(k)){
                            list.remove(k);
                        }
                        k++;
                    }
                    j++;
                }

                int newsize = list.size();

                //printing
                while (l < newsize){
                    temp = temp + " " + list.get(l);
                    l++;

                }

                MessageTo.message(ViewTasksActivity.this, temp);

            }
        });

    }

我的代码仅适用于此条件,例如:

list = {54,56,57,54}

然后点击提交以清除列表

list = {56,57} 正确

但有了这个条件

list = {54,55,57,58,55}

然后点击提交以清除列表

list = {54,55,57,58,55} INCORRECT 应删除55

list = {54,55,55,58,55}

然后点击提交以清除列表

list = {54,55,55,58,55} INCORRECT 应删除55但仍然只有一个55,应为{54,55,58}

------- -------更新

完整代码

public class ViewTasksActivity extends AppCompatActivity {

    private GridLayout gridLayout;
    private Button b,checked;
    private CheckBox cb;

    ArrayList<Integer> list;

    public int goal_id,actid;
    int rowIndex = 1;
    int colIndex = 0;
    int rowIndex2 = 1;
    int colIndex2 = 1;
    int rowIndex3 = 1;
    int colIndex3 = 2;


    int i=0;



    MyDBAdapter dbhandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_tasks);

        Bundle extras = getIntent().getExtras();

        if (extras == null) {
            return;
        }

        //layout variables
        gridLayout = (GridLayout) findViewById(R.id.taskListLayout);
        checked = (Button)  findViewById(R.id.checktasks);

        goal_id = Integer.parseInt(extras.getString("goalid"));
        actid = Integer.parseInt(extras.getString("activityId"));

        list = new ArrayList<Integer>();

        dbhandler = new MyDBAdapter(this);

        set = new HashSet<>();

        displayAllTasks();
        submit();
    }

    public void displayAllTasks(){
        //get a list of all tasks
        List<Tasks> allTasks = dbhandler.getAllTasksbyActivity(goal_id,actid);

        for (final Tasks task : allTasks){

            //task name
            TextView textView2 = new TextView(ViewTasksActivity.this);
            GridLayout.LayoutParams param3 = new GridLayout.LayoutParams();
            param3.rowSpec = GridLayout.spec(rowIndex);
            param3.columnSpec = GridLayout.spec(colIndex);
            textView2.setTextColor(Color.BLACK);
            textView2.setLayoutParams(param3);
            textView2.setText(task.getTaskName());

            //status
            TextView textView = new TextView(ViewTasksActivity.this);
            GridLayout.LayoutParams param = new GridLayout.LayoutParams();
            param.rowSpec = GridLayout.spec(rowIndex2);
            param.columnSpec = GridLayout.spec(colIndex2);
            textView.setTextColor(Color.BLACK);
            textView.setLayoutParams(param);

            if(task.getComplete().equalsIgnoreCase("False")){
                cb = new CheckBox(ViewTasksActivity.this);
                GridLayout.LayoutParams param4 = new GridLayout.LayoutParams();
                param4.rowSpec = GridLayout.spec(rowIndex3);
                param4.columnSpec = GridLayout.spec(colIndex3);
                param4.setMargins(30, 5, 5, 5);
                cb.setLayoutParams(param4);
                cb.setId(task.getTaskId());
                cb.setClickable(Boolean.TRUE);

                textView.setText("   Incomplete");

                cb.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {
                            list.add(task.getTaskId());
                            i++;

                    }

                });

            }
            else
            {
                cb = new CheckBox(ViewTasksActivity.this);
                GridLayout.LayoutParams param5 = new GridLayout.LayoutParams();
                param5.rowSpec = GridLayout.spec(rowIndex3);
                param5.columnSpec = GridLayout.spec(colIndex3);
                param5.setMargins(30, 5, 5, 5);
                cb.setLayoutParams(param5);
                textView.setText("   Complete");
                cb.setId(task.getTaskId());
                cb.isChecked();
                cb.setClickable(Boolean.FALSE);




            }

            gridLayout.addView(textView);
            gridLayout.addView(textView2);
            gridLayout.addView(cb);
            rowIndex3++;
            rowIndex2++;
            rowIndex++;
        }


    }

    public void submit(){
        checked.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int j = 0;
                    int k = 1;
                    int l =0;
                    int size = list.size();
                    String temp = "";

                    //removing common
                    while (j < size) {
                        while(k < size){
                            if(list.get(j) == list.get(k)){
                                list.remove(k);
                            }
                            k++;
                        }
                        j++;
                    }

                    int newsize = list.size();

                    //printing
                    while (l < newsize){
                        temp = temp + " " + list.get(l);
                        l++;

                    }

                    MessageTo.message(ViewTasksActivity.this, temp);

            }
        });

    }



    public void goBack(){
        Intent myIntent = new Intent(ViewTasksActivity.this, ViewActActivity.class);
        myIntent.putExtra("goalid", Integer.toString(goal_id));
        startActivity(myIntent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_view_tasks, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_back) {
            goBack();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

5 个答案:

答案 0 :(得分:0)

您没有重置索引&#39; k&#39;每次循环后。 所以目前它只检查第一个元素而不是其他所有元素...... 你需要添加:

    while (j < size) {
        // Add k = 0; here
        k = 0;
        while(k < size)

答案 1 :(得分:0)

如果您要删除相同值的,以便[1, 1, 2]变为[2],但[1, 1, 1, 2]变为[1, 2],则可以使用这样Set

// list contains [1, 2, 3, 4, 2, 3, 2]

Set<Integer> set = new HashSet<>();

for (Integer i : list) {
    if (set.contains(i)) {
        set.remove(i);
    } else {
        set.add(i);
    }
}

list.clear();
list.addAll(set);
System.out.println(list); // [1, 2, 4]

如果您想保留订单,请改用LinkedHashSet

答案 2 :(得分:0)

public ArrayList<int> cleanList(ArrayList<int> list){
  ArrayList<int> newList = new ArrayList<int>();
  for(int i = 0; i < list.size(); i++){
    int item = list.get(i);
    if(!newList.contains(item)){
      newList.add(item);
    }
  }
  return newList;
}

下面的几个答案建议使用我同意的Set,但如果您出于某种原因需要使用ArrayList,那么干净利落的方式就是明确的。只有一个循环遍历列表并返回一个已清理的新ArrayList。

答案 3 :(得分:0)

您可以通过再次循环 arrayList 来删除项目。但它又增加了时间复杂度。

为什么不使用集合,禁止使用重复的元素。

Set<Integer> set = new HashSet<Integer>();
set.add();

答案 4 :(得分:0)

在下面有一种删除重复值的替代方法。我在我的代码中添加了评论。

public static void main(String[] args) {

    ArrayList<Integer> myList = new ArrayList<Integer>();

    myList.addAll(Arrays.asList(new Integer[] { 33, 34, 34, 33 }));

    System.out.println(removeDuplicateValues(myList));
}

public static ArrayList<Integer> removeDuplicateValues(ArrayList<Integer> list) {
    Integer[] myList = new Integer[list.size()];
    myList = list.toArray(myList); // we should copy our array at the first because we will modify the original one in the loop.
    for (Integer integer : myList) {
        list.remove(integer); // first remove the integer
        if (!list.contains(integer))
            list.add(integer); // add it again if it does not exist afer removing.
    }
    return list;
}
  

打印:[33,34]而我们的arraylist有值:[33,34,34,33]

如果要删除所有重复值:

public static void main(String[] args) {
    ArrayList<Integer> myList = new ArrayList<Integer>();
    myList.addAll(Arrays.asList(new Integer[] { 35, 34, 34, 33 }));
    System.out.println(removeAllDublicateValues(myList));
}

public static ArrayList<Integer> removeAllDuplicateValues(ArrayList<Integer> list) {
    Integer[] myList = new Integer[list.size()];
    myList = list.toArray(myList); // we should copy our array at the first because we will modify the original one in the loop.

    List<Integer> duplicateList = new ArrayList<Integer>();

    for (Integer integer : myList) {
        list.remove(integer); // first remove the integer
        if (!list.contains(integer) && !duplicateList.contains(integer))
            list.add(integer); // add it again if it does not exist afer removing. And it is not a diplicate value
        else 
            duplicateList.add(integer);

    }
    return list;
}
  

打印:[35,33]而我们的arraylist有值:[35,34,34,33]