導航:首頁 > 編程語言 > 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數組相同元素個數組相關的資料

熱點內容
榮耀手機的系統有方舟編譯器嗎 瀏覽:629
單片機應用的論文 瀏覽:474
什麼app可以查網購的真偽 瀏覽:444
培訓班的程序員怎麼樣找工作 瀏覽:813
codeblocks編譯器位數 瀏覽:447
bios加密怎麼設置 瀏覽:349
台電u盤加密大師損壞 瀏覽:850
secure網站加密 瀏覽:124
電視顯示加密是怎麼回事 瀏覽:6
hadoophdfs書籍源碼 瀏覽:584
電極伺服器什麼意思 瀏覽:10
MI預編譯系統 瀏覽:596
python數據篩選教程 瀏覽:965
dell伺服器怎麼風扇一直叫 瀏覽:27
巴巴騰使用什麼APP 瀏覽:216
程序員與it 瀏覽:805
農民種地用什麼app 瀏覽:665
視頻彩鈴為什麼伺服器升級失敗 瀏覽:588
前端程序員轉正自我評價 瀏覽:314
單片機開發有創新點嗎 瀏覽:114