我有两个类,一个是News类,有两个属性Stirng title,String content.
还有一个NewsList类,有一个属性 Set<News> newslist;
问题是我往set里面加入一条新闻,这条新闻的标题必须是集合中没有的才能加进去,请问算法该怎么实现啊,修改,删除都比较容易,但是如何写增加?求助一下!!
------解决方案--------------------
重写 hashCode()和equals()方法
- Java code
package com.xiaoqi;public class News { String title; String content; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((content == null) ? 0 : content.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; News other = (News) obj; if (content == null) { if (other.content != null) return false; } else if (!content.equals(other.content)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; }}
------解决方案--------------------