KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > util > ContainUtil


1 /*
2  * Copyright (c) 2002-2003 by OpenSymphony
3  * All rights reserved.
4  */

5 package com.opensymphony.webwork.util;
6
7 import java.lang.reflect.Array JavaDoc;
8 import java.util.Collection JavaDoc;
9 import java.util.Map JavaDoc;
10
11
12 /**
13  * <code>ContainUtil</code> will check if object 1 contains object 2.
14  * Object 1 may be an Object, array, Collection, or a Map
15  *
16  * @author Matt Baldree (matt@smallleap.com)
17  * @version $Revision: 1.3 $
18  */

19 public class ContainUtil {
20     //~ Methods ////////////////////////////////////////////////////////////////
21

22     public static boolean contains(Object JavaDoc obj1, Object JavaDoc obj2) {
23         if ((obj1 == null) || (obj2 == null)) {
24             //log.debug("obj1 or obj2 are null.");
25
return false;
26         }
27
28         if (obj1 instanceof Map JavaDoc) {
29             if (((Map JavaDoc) obj1).containsValue(obj2)) {
30                 //log.debug("obj1 is a map and contains obj2");
31
return true;
32             }
33         } else if (obj1 instanceof Collection JavaDoc) {
34             if (((Collection JavaDoc) obj1).contains(obj2)) {
35                 //log.debug("obj1 is a collection and contains obj2");
36
return true;
37             }
38         } else if (obj1.getClass().isArray()) {
39             for (int i = 0; i < Array.getLength(obj1); i++) {
40                 Object JavaDoc value = null;
41                 value = Array.get(obj1, i);
42
43                 if (value.equals(obj2)) {
44                     //log.debug("obj1 is an array and contains obj2");
45
return true;
46                 }
47             }
48         } else if (obj1.equals(obj2)) {
49             //log.debug("obj1 is an object and equals obj2");
50
return true;
51         }
52
53         //log.debug("obj1 does not contain obj2: " + obj1 + ", " + obj2);
54
return false;
55     }
56 }
57
Popular Tags