`

List.contains(Object object)方法

阅读更多

  使用List.contains(Object object)方法判断ArrayList是否包含一个元素对象(针对于对象的属性值相同,但对象地址不同的情况),如果没有重写List<E>的元素对象Object中的equals方法,默认如下:

@Override
public boolean equals(Object o) {
	// TODO Auto-generated method stub
	return super.equals(o);
}

  将导致contains方法始终返回false。

  查看ArrayList的contains方法的源码如下:

/**
 * Searches this {@code ArrayList} for the specified object.
 *
 * @param object
 *            the object to search for.
 * @return {@code true} if {@code object} is an element of this
 *         {@code ArrayList}, {@code false} otherwise
 */
@Override public boolean contains(Object object) {
	Object[] a = array;
	int s = size;
	if (object != null) {
		for (int i = 0; i < s; i++) {
			if (object.equals(a[i])) {
				return true;
			}
		}
	} else {
		for (int i = 0; i < s; i++) {
			if (a[i] == null) {
				return true;
			}
		}
	}
	return false;
}

  可以看出,contains方法依据Object的equals方法来判断是否包含某一元素,继续查看Object类中的equals方法,源码如下:

public boolean equals(Object o) {
	return this == o;
}

  所以,使用“==”比较对象的地址,如果是同一对象即地址相同的情况下,才会返回true,而对于对象属性值相同但地址不同的不同对象,始终返回false!

  如果需要依据对象属性值是否相同来判断ArrayList是否包含某一对象,则需要重写Object的equals方法,并在equals方法中一一比较对象的每个属性值,如:

public class QuestionInfo {
 
	private String questionId;
	
	private String answerId;
	
	private String subQuestionId;
	
	private String result;
 
	public QuestionInfo() {
		super();
		
	}
 
	public QuestionInfo(String questionId, String answerId,
			String subQuestionId, String result) {
		super();
		this.questionId = questionId;
		this.answerId = answerId;
		this.subQuestionId = subQuestionId;
		this.result = result;
	}
 
	public String getQuestionId() {
		return questionId;
	}
 
	public void setQuestionId(String questionId) {
		this.questionId = questionId;
	}
 
	public String getAnswerId() {
		return answerId;
	}
 
	public void setAnswerId(String answerId) {
		this.answerId = answerId;
	}
 
	public String getSubQuestionId() {
		return subQuestionId;
	}
 
	public void setSubQuestionId(String subQuestionId) {
		this.subQuestionId = subQuestionId;
	}
 
	public String getResult() {
		return result;
	}
 
	public void setResult(String result) {
		this.result = result;
	}
 
	@Override
	public boolean equals(Object o) {
		if (o instanceof QuestionInfo) {
			QuestionInfo question = (QuestionInfo) o;
			return this.questionId.equals(question.questionId)
					&& this.subQuestionId.equals(question.subQuestionId)
					&& this.answerId.equals(question.answerId)
					&& this.result.equals(question.result);
		}
		return super.equals(o);
	}
	
	@Override
	public String toString() {
		return "QuestionInfo [questionId=" + questionId + ", answerId="
				+ answerId + ", subQuestionId=" + subQuestionId + ", result="
				+ result + "]";
	}
}

 

PS:《浅谈Arrays.asList()方法的使用》一文有用到List.contains,有兴趣的可以阅读。

 

文章来源:https://blog.csdn.net/growing_tree/article/details/46622579

分享到:
评论

相关推荐

    json的解析

    JSONArray jsonArray2 = JSONArray.fromObject( list ); System.out.println( jsonArray2 ); // prints ["first","second"] /*String生成json数组*/ JSONArray jsonArray3 = JSONArray.fromObject( "['...

    lodash underscore js库速查手册

    Collection Functions (Arrays or Objects) _.each(list, iterator, [context]) Alias: forEach Iterates ... Useful for transmuting the arguments object. _.size(list) Return the number of values in the list.

    Json解析ParsreTools.zip

    } else if (type.contains("java.util.List")) { int index1 = type.indexOf("); int index2 = type.indexOf("&gt;"); type = type.substring(index1 + 1, index2); Class cls1 = Class.for...

    2012RobocupRuscue东大代码

    import seu.object.Road.MultiBlockDistanceComparator; import seu.object.Road.RoadInfo; import seu.object.Road.RoadUtilities; import seu.utilities.DistanceComparator; import seu.utilities.Path; import ...

    JavaScript权威指南

    Function Arguments: The Arguments Object Section 7.5. Function Properties and Methods Chapter 8. Objects Section 8.1. Objects and Properties Section 8.2. Constructors Section 8.3. Methods...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - FIX: In "Windows ClearType" font rendering mode (OS Windows mode) the "garbage" pixels can appear from the right and from the bottom sides of the painted rectangle of the TFlexText object....

    欧拉回路程序java

    return this.adjacencyList.contains(new SNode(i)); } public void removeAdjacencyNode(int i) { this.adjacencyList.remove(new SNode(i)); } public void addAdjacencyNode(int i) { this....

    Developing Flex Applications 910p dda_doc88_cracker.zip

    This package contains 3 kid: 1. a book Developing Flex Applications 2. a web page viewer for doc88 ebt 3. a DDA downloader for doc88.com CONTENTS PART I: Presenting Flex CHAPTER 1: Introducing ...

    jor:Java 对象记录库

    // return the List.add(Object) methodrecorder.getRecordings().get(0).getMethod();List&lt;String&gt; replayList = new ArrayList();recorder.replayOn(replayList);// now replayList contains ["one", "two"]真实...

    The way to go

    go程序设计语言 Contents Preface................................................................................................................................. xix PART 1—WHY LEARN GO—GETTING ...

    [Go语言入门(含源码)] The Way to Go (with source code)

    The Way to Go,: A Thorough Introduction to the Go Programming Language 英文书籍,已Cross the wall,从Google获得书中源代码,分享一下。喜欢请购买正版。 目录如下: Contents Preface......................

    Word Amalgamation

    The object of this game is to solve a riddle, but in order to find the letters that appear in the answer it is necessary to unscramble four words. Your task is to write a program that can unscramble ...

    servlet2.4doc

    The default behavior of this method is to call containsHeader(String name) on the wrapped response object. containsHeader(String) - Method in interface javax.servlet.http.HttpServletResponse Returns...

    最新Ehlib 5.2.84(含完整源代码,支持delphi XE)

    Write this event to fill list of droped down list of STFilter cell. You can can call default event handler DefaultFillSTFilterListValues. Every item of list Items must consist from to elements: ...

    Excel POI读取封装(文件+示范代码)

    List, Object&gt;&gt; list = new ArrayList, Object&gt;&gt;(); HashMap, Object&gt; datamap = null; DealForeign deal = null; // 存放带验证信息的属性 Map, String&gt; iscompare = new HashMap, String&gt;(); for (Map...

    JAVA集合(List,Set,Map)

    Java 2集合框架图 集合接口:6个接口(短虚线表示),表示不同集合类型,是集合框架的基础。 抽象类:5个抽象类(长虚线表示)...:判断集合中是否有任何元素 boolean contains(Object o) :查找集合中是否含有对象o

    一个ASP.NET的JS管理方案,防止重复引用JS问题

    场景:在自定义控件、... protected void Page_Load(object sender, EventArgs e)  {  JavaScriptManager.JavaScriptManager.Include("~/JS/cs.js",  "~/JS/cs.js",  "~/JS/cs.js2",  "~/JS/cs.js");  } }

    PLSQL.Developer(X64) v12.0.1.1814 主程序+ v11中文包+keygen

    The Quick Access Toolbar above the ribbon contains the most frequently used functions, so that they are always immediately available. You can customize the Quick Access Toolbar to your own liking. ...

    C#语法及存储过程.docx

    object obj = command.ExecuteScalar(); if (obj != null) { single = command.ExecuteScalar().ToString(); } } catch { } } } return single; } /// /// 返回查询到的行数 /// /// ...

    C# Game Programming Cookbook for Unity 3D - 2014

    4.9 Automatic Object Spinner............................................79 4.9.1 Script Breakdown..........................................80 ix Contents 4.10 Scene Manager...............................

Global site tag (gtag.js) - Google Analytics