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

huangapple go评论73阅读模式
英文:

Prevent to add data in ArrayList of type Class

问题

以下是代码的中文翻译:

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, "已存在", 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 + " 已删除", Snackbar.LENGTH_LONG)
                    .setAction("撤销", 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("添加科目名称");
                b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

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

                        if (text.isEmpty()) {
                            Toast.makeText(ScrollingActivity.this, "请添加科目名称", Toast.LENGTH_SHORT).show();
                        } else {
                            insertItem(text);
                            saveData();
                        }
                    }
                });
                b.setCancelable(false);
                b.show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        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("科目名称", mExampleList.get(position).getText1());
        startActivity(i);
    }
}
英文:

How can i prevent the dublicate data to be added in my ArrayList of class

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

I am using this code to prevent the adding of dublicate elements but it&#39;s not working 

Code

public class ScrollingActivity extends AppCompatActivity implements AdaptreForRecycler.OnItemClickListener {
private RecyclerView recyclerView;
private AdaptreForRecycler adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList&lt;ExampleItem&gt; 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(&quot;SHARED_PREFS&quot;, MODE_PRIVATE);
editor = sharedPreferences.edit();
gson = new Gson();
json = gson.toJson(mExampleList);
editor.putString(&quot;text&quot;, json);
editor.apply();
}
public void loadData() {
sharedPreferences = getSharedPreferences(&quot;SHARED_PREFS&quot;, MODE_PRIVATE);
gson = new Gson();
json = sharedPreferences.getString(&quot;text&quot;, null);
type = new TypeToken&lt;ArrayList&lt;ExampleItem&gt;&gt;() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList&lt;&gt;();
}
}
public void insertItem(String text) {
ExampleItem ex = new ExampleItem(text);
if ( mExampleList.contains(ex)) {
Toast.makeText(this, &quot;Already Exists&quot;, 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(&quot;SHARED_PREFS&quot;, MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.remove(&quot;text&quot;);
saveData();
editor.apply();
adapter.notifyItemRemoved(position);
Snackbar.make(recyclerView, name + &quot; Deleted&quot;, Snackbar.LENGTH_LONG)
.setAction(&quot;Undo&quot;, 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(&quot;Add subject name&quot;);
b.setNegativeButton(&quot;cancel&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
b.setPositiveButton(&quot;ok&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString();
if (text.isEmpty()) {
Toast.makeText(ScrollingActivity.this, &quot;Please add subject name&quot;, 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(&quot;Subject Name&quot;, mExampleList.get(position).getText1());
startActivity(i);
}

}

答案1

得分: 0

我猜你想要防止重复元素被添加到 ArrayList 中。但这并不是 ArrayList 的优势所在。如果你只想保留唯一的元素,可以使用 HashSet 数据结构,它只会保留不重复的元素。
但需要额外注意的是,你如何定义重复,是两个元素具有相同的内容,还是它们具有相同的 ID(即完全相同的对象)。

英文:

I am guessing you want to prevent duplicated elements to be added to ArrayList. But it is not ArrayList's strength. If you want to keep just unique elements, just use the HashSet data structure which will only retain unique elements.
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).

答案2

得分: 0

是的,这是可能的,你可以在扫描val变量之后使用arrayList.contains(val)

如果它返回1,那么打印"val already exists.",否则,

如果它返回0,那么你可以将它添加到arrayList中。

查看.contains()方法的工作原理

你还可以使用.indexOf()方法来找出位置。参见这里

要在对象上使用.contains(),你需要重写hashCodeequals方法。参见这里,查看标记答案的评论

英文:

Yes it is possible, you can use arrayList.contains(val) after scanning the val variable.

If it return 1, then print("val already exits.") otherwise,

If it returns 0, then you can add it in the arrayList

See how .contains() method work

You can also use .indexOf() method to find out the position. Refer here

To use .contains() with an Object You need to override hashcode and equals method . Refer here, watch the comments of marked Answer

答案3

得分: 0

这个解决方案是从这篇帖子中进一步扩展而来的。Unique value ArrayList
它具有数组列表的所有行为,因为您可以像 ArrayList 一样添加和检索元素,但同时保持唯一性。
以下是您可以自己创建的 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);
    }
}
英文:

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.
Below is the code of the ArrayListSet that you can create on your own.

import java.util.*;
public class ArrayListSet&lt;E&gt; implements Iterable&lt;E&gt;, Set&lt;E&gt; {
private ArrayList&lt;E&gt; list;
private HashSet&lt;E&gt; set;
public ArrayListSet() {
list = new ArrayList&lt;&gt;();
set = new HashSet&lt;&gt;();
}
public boolean add(E e) {
return set.add(e) &amp;&amp; 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&lt;? super E&gt; c) {
Collections.sort(list, c);
}
public Iterator&lt;E&gt; iterator() {
return list.iterator();
}
public boolean addAll(Collection&lt;? extends E&gt; c) {
int before = size();
for (E e : c) add(e);
return size() == before;
}
public boolean containsAll(Collection&lt;?&gt; c) {
return set.containsAll(c);
}
public boolean removeAll(Collection&lt;?&gt; c) {
return set.removeAll(c) &amp;&amp; list.removeAll(c);
}
public boolean retainAll(Collection&lt;?&gt; c) {
return set.retainAll(c) &amp;&amp; list.retainAll(c);
}
public Object[] toArray() {
return list.toArray();
}
public &lt;T&gt; T[] toArray(T[] a) {
return list.toArray(a);
}
}

答案4

得分: 0

有一种相当简单的方法来检查列表中是否已存在一个项目:

重写equals方法。

您需要在ExampleItem类内部重写equals方法。

我不知道您的ExampleItem的内容,即代码,但这只是我的猜测,建议您相应地更改您的代码。

public class ExampleItem {

    private String text1, text2;

    @Override
    public boolean equals(Object o) {
        // 检查给定的对象'o'是否是此ExampleItem类的实例,
        // 即相同的类
        if (o instanceof ExampleItem) {
            // 将对象强制转换为ExampleItem
            ExampleItem other = (ExampleItem) o;

            // 检查两者是否具有相同的文本
            // (我猜您只想比较text1变量,否则请查看下面的注释。)
            // Objects.equals()将评估两者的文本是否相同
            return Objects.equals(this.text1, other.text1); // 'this'是不必要的,仅用于显示

            // 如果要检查两者,取消注释下面的代码并删除上面的代码
            // return Objects.equals(text1, other.text1) && Objects.equals(text2, other.text2);
        }

        // 如果上面的检查失败,那么我将使用
        // 先前重写的equals以避免
        // 自己编写每一点
        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;
    }

}

然后,Listcontains方法将使用您重写/自定义的equals方法来比较给定的项目与其中的其他项目。

就是这样,就像一种即插即用的代码一样。您现在可以期望mExampleList.contains(ex)能够正常工作。

当然,我希望它能够正常工作,一如既往,祝愿编码愉快!

英文:

There's a pretty simple way to check if an item already exists in the list:

Override the equals method.

You will have to override the equals method inside your ExampleItem class.

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.

public class ExampleItem {
private String text1, text2;
@Override
public boolean equals(Object o) {
// Check if the given Object &#39;o&#39; 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&#39;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); // &#39;this&#39; 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) &amp;&amp; Objects.equals(text2, other.text2);
}
// If above fails then I&#39;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.

And that's it, just like a plug-and-play kinda code thing. You can now expect your mExampleList.contains(ex) to work.

And surely I hope that it does work and as always, happy coding!

huangapple
  • 本文由 发表于 2020年5月5日 12:35:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/61605866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定