如何从Java中的arraylist返回特定的对列表 [英] How to return a specific list of pairs from an arraylist in Java

查看:49
本文介绍了如何从Java中的arraylist返回特定的对列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下整数列表



(0,1,2,3)



现在我想编写一个方法,从列表中返回特定数量的对。因此,如果我将它作为参数给出5,我将期望它返回以下内容:



(0,1),(1,2) ,(2,3),(3,0),(0,1)



所以基本上当它到达end元素并且需要另一对时,它应该是将列表的最后一个元素与第一个元素配对并继续。



任何想法如何实现?

解决方案

你最好自己弄明白。



 import java.util.ArrayList; 

public class Main {

public static void main( String [] args){
// TODO自动生成方法存根
int [] list = { 0 1 2 3 };
int num = 5 ;
ArrayList< int [] > results = getPairs(list,num);
for int [] tmp:results){
System。 out .println( + tmp [ 0 ] + + tmp [ 1 ] + ) ;
}

}

私人 静态 ArrayList< int [] > getPairs( int [] list, int num){
ArrayList< int [] > results = new ArrayList< int [] > ();
int len = list.length;
int index = 0 ;
for int i = 0 ; i < num; i ++){
if ((index + 1 > = len){
results。添加 new int [] {list [index],list [ 0 ]});
index = 0 ;
}
其他 {
results。 add new int [] {list [index],list [index + 1 ]});
++指数;
}
}
返回结果;
}
}





这是输出:

(0,1)
(1,2)
(2,3)
(3,0)
(0,1)


I have the following list of Integers

(0,1,2,3)


Now I want to write a method which returns specific number of pairs from the list. So if I give it 5 as argument I will expect it to return the following:

(0,1),(1,2),(2,3),(3,0),(0,1)


So basically when it reaches the end element and another pair is needed, then it should pair the last element of the list with the first one and continue.

Any ideas how can I implement this?

解决方案

You'd better try to figure it out by yourself.

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] list = {0,1,2,3};
        int num = 5;
        ArrayList<int[]> results = getPairs(list, num);
        for (int[] tmp : results) {
            System.out.println("(" + tmp[0] + ","+ tmp[1] + ")");
        }

    }

    private static ArrayList<int[]> getPairs(int[] list, int num) {
        ArrayList<int[]> results = new ArrayList<int[]>();
        int len = list.length;
        int index = 0;
        for (int i = 0; i < num; i++) {
            if ((index + 1) >= len) {
                results.add(new int[]{list[index], list[0]});
                index = 0;
            }
            else {
                results.add(new int[]{list[index], list[index + 1]});
                ++index;
            }
        }
        return results;
    }
}



Here is the ouput:

(0,1)
(1,2)
(2,3)
(3,0)
(0,1)


这篇关于如何从Java中的arraylist返回特定的对列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆