简体   繁体   English

防止在 Class 类型的 ArrayList 中添加数据

[英]Prevent to add data in ArrayList of type Class

How can i prevent the dublicate data to be added in my ArrayList of class如何防止在classArrayList中添加重复数据

When i will add a data to array list then it will check that whether it is dublicate or not if yes it will not add the data to ArrayList当我将数据添加到数组列表时,它将检查它是否重复,如果是,它不会将数据ArrayListArrayList

I am using this code to prevent the adding of dublicate elements but it's not working 

Code代码

public class ScrollingActivity extends AppCompatActivity implements AdaptreForRecycler.OnItemClickListener {
private RecyclerView recyclerView;
private AdaptreForRecycler adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<ExampleItem> mExampleList;


private Gson gson;
private String json;
private Type type;

private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;


EditText editText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scrolling);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    loadData();
    buildRecyclerView();

    editText = findViewById(R.id.editText);
    fabButoonClick();


}

public void saveData() {

    sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
    editor = sharedPreferences.edit();
    gson = new Gson();
    json = gson.toJson(mExampleList);

    editor.putString("text", json);
    editor.apply();

}

public void loadData() {

    sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
    gson = new Gson();
    json = sharedPreferences.getString("text", null);
    type = new TypeToken<ArrayList<ExampleItem>>() {
    }.getType();
    mExampleList = gson.fromJson(json, type);

    if (mExampleList == null) {
        mExampleList = new ArrayList<>();
    }

}


public void insertItem(String text) {

    ExampleItem ex = new ExampleItem(text);


    if ( mExampleList.contains(ex)) {
        Toast.makeText(this, "Already Exists", Toast.LENGTH_SHORT).show();
    } else {
        mExampleList.add(ex);
    }

    adapter.notifyDataSetChanged();


}

ExampleItem deletedIndex = null;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
        return false;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        final int position = viewHolder.getAdapterPosition();
        String name = mExampleList.get(position).getText1();
        deletedIndex = (mExampleList.get(position));
        mExampleList.remove(position);

        sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.remove("text");

        saveData();

        editor.apply();
        adapter.notifyItemRemoved(position);

        Snackbar.make(recyclerView, name + " Deleted", Snackbar.LENGTH_LONG)
                .setAction("Undo", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mExampleList.add(position, deletedIndex);
                        adapter.notifyItemInserted(position);

                        saveData();

                    }
                }).show();
    }

    @Override
    public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {

        new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)

                .addSwipeLeftBackgroundColor(ContextCompat.getColor(ScrollingActivity.this, R.color.my_background))
                .addSwipeLeftActionIcon(R.drawable.ic_delete_black_24dp)
                .create()
                .decorate();
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }
};


private void buildRecyclerView() {
    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(ScrollingActivity.this);
    adapter = new AdaptreForRecycler(this, mExampleList);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);

    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);

}

public void fabButoonClick() {
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            AlertDialog.Builder b = new AlertDialog.Builder(ScrollingActivity.this);
            View mview = getLayoutInflater().inflate(R.layout.dialogbox_frontpage, null);

            final EditText editText = mview.findViewById(R.id.editText);
            b.setView(mview);
            b.setTitle("Add subject name");
            b.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String text = editText.getText().toString();

                    if (text.isEmpty()) {
                        Toast.makeText(ScrollingActivity.this, "Please add subject name", Toast.LENGTH_SHORT).show();
                    } else {

                        insertItem(text);

                        saveData();
                    }
                }
            });
            b.setCancelable(false);
            b.show();
        }
    });

}

@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_scrolling, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();


    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onItemClick(int position) {
    Intent i = new Intent(ScrollingActivity.this, StudentListActivity.class);
    i.putExtra("Subject Name", mExampleList.get(position).getText1());

    startActivity(i);
}

} }

I am guessing you want to prevent duplicated elements to be added to ArrayList .我猜您想防止将重复的元素添加到ArrayList But it is not ArrayList 's strength.但这不是ArrayList的强项。 If you want to keep just unique elements, just use the HashSet data structure which will only retain unique elements.如果您只想保留唯一元素,只需使用仅保留唯一元素的HashSet数据结构。 But what need extra attention is that how you define duplicates, whether two elements has same contents or they have same id(which is exactly the same object).但需要特别注意的是如何定义重复项,两个元素是否具有相同的内容或它们具有相同的 id(即完全相同的对象)。

Yes it is possible, you can use arrayList.contains(val) after scanning the val variable.是的,有可能,您可以在扫描 val 变量后使用arrayList.contains(val)

If it return 1 , then print("val already exits.") otherwise,如果它return 1 ,则 print("val already exits.") 否则,

If it returns 0 , then you can add it in the arrayList如果returns 0 ,则可以将其添加到 arrayList

See how.contains() method work查看.contains() 方法的工作原理

You can also use.indexOf() method to find out the position.您也可以使用 .indexOf() 方法找出 position。 Refer here 参考这里

To use.contains() with an Object You need to override hashcode and equals method.要将.contains() 与 Object 一起使用,您需要覆盖 hashcode 和 equals 方法。 Refer here, watch the comments of marked Answer 参考这里,观看标记答案的评论

This solution is a further extension adopted from this post.此解决方案是本文采用的进一步扩展。 Unique value ArrayList It has all behaviors of array list since you can add and retrieve element as an ArrayList but keep uniqueness at the same time. 唯一值 ArrayList它具有数组列表的所有行为,因为您可以将元素作为 ArrayList 添加和检索,但同时保持唯一性。 Below is the code of the ArrayListSet that you can create on your own.下面是您可以自己创建的ArrayListSet的代码。

import java.util.*;

public class ArrayListSet<E> implements Iterable<E>, Set<E> {
    private ArrayList<E> list;
    private HashSet<E> set;

    public ArrayListSet() {
        list = new ArrayList<>();
        set = new HashSet<>();
    }

    public boolean add(E e) {
        return set.add(e) && list.add(e);
    }

    public boolean add(int i, E e) {
        if (!set.add(e)) return false;
        list.add(i, e);
        return true;
    }

    public void clear() {
        list.clear();
        set.clear();
    }

    public boolean contains(Object o) {
        return set.contains(o);
    }

    public E get(int i) {
        return list.get(i);
    }

    public boolean isEmpty() {
        return list.isEmpty();
    }

    public E remove(int i) {        
        E e = list.remove(i);
        set.remove(e);
        return e;
    }

    public boolean remove(Object o) {        
        if (set.remove(o)) {
            list.remove(o);
            return true;
        }

        return false;
    }

    public boolean set(int i, E e) {
        if (set.contains(e)) return false;

        set.add(e);
        set.remove(list.set(i, e));
        return true;
    }

    public int size() {
        return list.size();
    }

    public void sort(Comparator<? super E> c) {
        Collections.sort(list, c);
    }

    public Iterator<E> iterator() {
        return list.iterator();
    }

    public boolean addAll(Collection<? extends E> c) {
        int before = size();
        for (E e : c) add(e);
        return size() == before;
    }

    public boolean containsAll(Collection<?> c) {
        return set.containsAll(c);
    }

    public boolean removeAll(Collection<?> c) {
        return set.removeAll(c) && list.removeAll(c);
    }

    public boolean retainAll(Collection<?> c) {
         return set.retainAll(c) && list.retainAll(c);
    }

    public Object[] toArray() {
        return list.toArray();
    }

    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }
}

There's a pretty simple way to check if an item already exists in the list:有一种非常简单的方法可以检查列表中是否已存在项目:

Override the equals method.覆盖equals方法。

You will have to override the equals method inside your ExampleItem class.您必须在ExampleItem class 中覆盖equals方法。

I don't know the contents, ie.我不知道内容,即。 code, of your ExampleItem but this is just my guess so I suggest you to change your code accordingly.您的ExampleItem的代码,但这只是我的猜测,所以我建议您相应地更改代码。

public class ExampleItem {

    private String text1, text2;

    @Override
    public boolean equals(Object o) {
        // Check if the given Object 'o' is an instance,
        // ie. same class, of this ExampleItem class
        if (o instanceof ExampleItem) {
            // Cast the object to ExampleItem
            ExampleItem other = (ExampleItem) o;

            // Check if both have same text
            // (I'm guessing that you only wanted to
            //   compare the text1 variable, otherwise,
            //   check comment below.)
            // Objects.equals() will evaluate whether
            // both text are the same
            return Objects.equals(this.text1, other.text1); // 'this' is unnecessary, only to show

            // If you want to check both then uncomment
            // the code below and remove the one above
            // return Objects.equals(text1, other.text1) && Objects.equals(text2, other.text2);
        }

        // If above fails then I'll just use the
        // before-overwritten equals to avoid
        // writing myself each tiny bit of
        // its implementation
        return super.equals(o);
    }

    public ExampleItem(String text1) {
        this.text1 = text1;
    }

    public ExampleItem(String text1, String text2) {
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getText1() {
        return text1;
    }

    public void setText1(String t1) {
        text1 = t1;
    }

    public String getText2() {
        return text2;
    }

    public void setText2(String t2) {
        text2 = t2;
    }

}

The contains method of the List then will use your overridden/custom equals method to compare the given item to other items in it.然后Listcontains方法将使用您的覆盖/自定义equals方法将给定项目与其中的其他项目进行比较。

And that's it, just like a plug-and-play kinda code thing.就是这样,就像即插即用的代码一样。 You can now expect your mExampleList.contains(ex) to work.您现在可以期望您的mExampleList.contains(ex)工作。

And surely I hope that it does work and as always, happy coding!当然,我希望它确实有效,并且一如既往地快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM