addAll函数正在复制列表中的对象

时间:2019-04-26 20:13:48

标签: java android list join

我的目标是将两个列表合并到一个列表中,但是问题是第一个列表的对象重复了两次,这是下面的代码:

List<Image> unionList = new ArrayList<Image>();

      unionList.addAll(fromImageList);

       unionList.addAll(fromTagList);

以便fromImageList的对象连接两次。

2 个答案:

答案 0 :(得分:0)

如果您只想汇总唯一的图像,则应使用Set

Set<Image> uniqueImages = new HashSet<>();

uniqueImages.addAll(fromImageList);

uniqueImages.addAll(fromTagList);

List<Image> unionList = new ArrayList<>(uniqueImages)

答案 1 :(得分:0)

执行 HashSet<string> phonearr = new HashSet<string>(); conn.Open(); MySqlCommand sda = new MySqlCommand("select * from members where Branch='" + lbladminbranch.Text + "' and Country='" + lbladmincountry.Text + "'", conn); MySqlDataReader dr = sda.ExecuteReader(); while (dr.Read()) { StringBuilder countrycode = new StringBuilder("44"); phonearr.Add(dr["Phone"].ToString()); foreach(string phone in phonearr) { countrycode.Append(phone); } txtsmsphoneno.Text = string.Join(",",countrycode ); } conn.Close(); 后,将创建一个空的arrayList。

执行List<Image> unionList = new ArrayList<Image>();后,fromImageList中的所有图像都将添加到unionList。

执行unionList.addAll(fromImageList);时,fromTagList中的所有图像都将添加到unionList。

ArrayList不会防止重复。如果要防止重复,则必须使用Set实现,例如HashSet。

您可以像下面这样

unionList.addAll(fromTagList);
相关问题