導航:首頁 > 編程語言 > java數組相同元素個數組

java數組相同元素個數組

發布時間:2023-04-24 09:14:59

A. java如何在一個整型數組里取相同的元素

int [] arr = {1,2,3,4};
//產生0-(arr.length-1)的整數值,也是數組的索引
int index=(int)(Math.random()*arr.length);
int rand = arr[index];

B. JAVA 遍歷數組,統計數組中包含幾個相同的元素

正則表達式: 不知道這樣算不算

int[] num={1,3,2,8,5,1,1,1};
String numstr = Arrays.toString(num);//把數組變成一個字元串[1, 3, 2, 8, 5, 5, 1, 1]
Pattern rex = Pattern.compile("1");//創建正則表達之對象匹配"1"
Matcher m = rex.matcher(numstr);// 匹配numstr字元串的匹配器
int count = 0;// 計數器,看匹配上了幾個
while(m.find()){ // find()方法從字元串中匹配"1" 找到返回true
count += 1; //找到1個 計數器值加 1
}
System.out.println(count);

C. java用程序實現求兩個數組中相同元素的個數

public class T
{
public static void main(String[] args)
{
int[] oneArray = {30, 1, 9, 20, 11, 15, 41,25,52,8};
int[] twoArray = {15, 7, 1, 30, 22, 13, 40,11,8,50};
int count=0;
boolean find;

for(int i=0;i<oneArray.length;i++)
{
find=false;
for(int j=0;j<twoArray.length;j++)
{
if(oneArray[i]==twoArray[j])
{
if(!find)
{
count++;
find=true;
}
twoArray[j]=-1;
}
}
}
System.out.println("數組oneArray與數組twoArray共有"+count+"個相同的元素!");
}
}

D. Java如何將數組中具有相同的元素都刪去

如果是要把List中的重復元素刪除的話可以先吧List轉成Set去除重復元素

比如現在有個數組為 myArray ,裡面有部分的重復元素

Set mySet = new HashSet();
for(Object obj : Array){
mySet.add(obj);
}

mySet中所保存的元素就是唯一的了.
再吧mySet保存到數組中

完整例子:
// 創建一個數組,裡面存在重復的元素
String[] myArray = {"s","s","f","d"};
Set<String> mySet = new HashSet<String>();
// 去除重復元素
for(String s : myArray){
mySet.add(s);
}
myArray = new String[mySet.size()];
int index = 0;
// 將去重後的結果存入數組
for(String s : mySet){
myArray[index] = s;
index++;
}
// 列印出來結果
System.out.println(Arrays.toString(myArray));

閱讀全文

與java數組相同元素個數組相關的資料

熱點內容
單片機怎麼做人臉識別 瀏覽:148
監獄辦理工商銀行app怎麼辦呢 瀏覽:813
c語言寫編程時需要用什麼輸入法 瀏覽:584
生發程序員 瀏覽:164
高考英語pdf 瀏覽:412
哈利波特忘記伺服器怎麼辦 瀏覽:818
怎麼看其他電腦共享文件夾 瀏覽:507
py文件夾後綴 瀏覽:717
你對我們的app有什麼建議 瀏覽:578
phpgetcookie 瀏覽:141
程序員最煩遇到的單詞 瀏覽:124
開始伺服器升級需要什麼 瀏覽:981
gcc中的編譯選項 瀏覽:189
程序員長沙開滴滴 瀏覽:138
十幾加幾的進位加法演算法 瀏覽:385
c語言實現字母加密成字母 瀏覽:329
linux重啟java服務 瀏覽:54
ubuntu的命令行在哪裡 瀏覽:981
伺服器tk是什麼意思 瀏覽:398
防止軟體加密碼卸載 瀏覽:183