当前位置: 移动技术网 > IT编程>开发语言>Java > java判定数组或集合是否存在某个元素的实例

java判定数组或集合是否存在某个元素的实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

傅莹的女儿婚礼图片,宜兴人事网,csol礼花

引言:

今天群里有朋友问“怎么知道一个数组集合是否已经存在当前对象”,大家都知道循环比对,包括我这位大神群友。还有没其他办法呢?且看此篇。

正文:

能找到这里的都是程序员吧,直接上代码应该更清楚些。

import java.io.serializable; 
import java.util.arraylist; 
import java.util.arrays; 
import java.util.collection; 
import java.util.regex.matcher; 
import java.util.regex.pattern; 
 
public class test implements serializable { 
 
  private static final long serialversionuid = 2640934692335200272l; 
 
  public static void main(string[] args) { 
 
    // data segment 
    string[] sample_array = new string[] { "aaa", "solo", "king" }; 
    string test_str = "king"; 
    collection template_coll = new arraylist(); 
    template_coll.add("aaa"); 
    template_coll.add("solo"); 
    template_coll.add("king"); 
    // <- data segment 
 
    // 1, 字符串数组是否存在子元素 
    // 1-1, 直接使用api 
    arrays.sort(sample_array); 
    int index = arrays.binarysearch(sample_array, test_str); 
    system.out.println("1-1_sort-binarysearche:" 
        + ((index != -1) ? true : false)); 
 
    // 1-2, 使用正则(因arrays.tostring()引入了“, [ ]”故只在有限环境下可靠) 
    string tmp = arrays.tostring(sample_array); 
    pattern p = pattern.compile("king"); 
    matcher m = p.matcher(tmp); 
    system.out.println("1-2_tostring-regex:" + m.find()); 
 
    // 1-3, 都会写循环,略过。 
    // todo: 循环数据依次比对,此处略去5行代码。 
 
    // 2, 集合是否存在子元素 
    // 2-1, 最常用的contains 
    system.out.println("2-1_contains:" + template_coll.contains(test_str)); 
 
    // 2-1-1, 扩展: 
    // 按模板集合,将当前集合分为“模板已存在”与“不存在”两个子集。 
    collection coll = new arraylist<string>(); 
    coll.add("aaa"); 
    coll.add("bbb"); 
    coll.add("ccc"); 
    // 完整复制集合 
    collection collexists = new arraylist(coll); 
    collection collnotexists = new arraylist(coll); 
 
    collexists.removeall(template_coll); 
    system.out.println("2-1-1_removeall[exist]:" + collexists); 
    collnotexists.removeall(collexists); 
    system.out.println("2-1-1_removeall[notexist]:" + collnotexists); 
 
  } 
 
} 

运行结果:

1-1_sort-binarysearche:true 
1-2_tostring-regex:true 
2-1_contains:true 
2-1-1_removeall[exist]:[bbb, ccc] 
2-1-1_removeall[notexist]:[aaa] 

小结一下吧~。=

1)数组至少三种:

    a)binarysearch(,)。但条件是需要事先排序,开销需要考虑。
    b)regex。但需要将数组转为字符串,arrays类提供的方法会引入“, [ ]”这三种分割符,可能影响判定结果。
    c)循环比对。

2)集合至少两种:

    a)循环。如果只是判定默认存在(非定制型存在),建议直接不考虑。
    b)contains。能靠过来就果断靠吧。

3)集合提供了类似“加减”的运算,可以留意一下。

以上就是小编为大家带来的java判定数组或集合是否存在某个元素的实例全部内容了,希望大家多多支持移动技术网~

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网