简体   繁体   English

Java 数组大小固定

[英]Java Array Size fixed

in Java I want to create an array with a fixed size, so I can add new Elements and the first Element drops out.Java我想创建一个固定大小的array ,这样我就可以添加新元素,而第一个元素会退出。

For example:例如:

The array with the size of 5 : {1,2,3,4,5} then I add " 6 " and the " 1 " drops out so I have {2,3,4,5,6} , the I add " 7 " and the " 2 " drops out: {3,4,5,6,7} ...大小为5array{1,2,3,4,5}然后我添加“ 6 ”和“ 1 ”退出所以我有{2,3,4,5,6} ,我添加“ 7 ”和“ 2 ”退出: {3,4,5,6,7} ...

So I want to add a new Element and remove the first Element.所以我想添加一个新元素并删除第一个元素。 Is there an easy way to do it or do I have to implement it myself?有没有简单的方法来做到这一点,还是我必须自己实施?

Can I do this with an ArrayList and just remove the first Object ?我可以使用ArrayList执行此操作并删除第一个Object吗? If I remove the first Object of an ArrayList , will the second Object automatically become the first object?如果我删除ArrayList的第一个Object ,第二个对象会自动成为第一个对象吗?

Thanks谢谢

Assuming that you don't need necessarily a List , you could use an EvictingQueue from Google Guava which is a non-blocking queue that automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.假设您不一定需要List ,您可以使用来自Google GuavaEvictingQueue ,它是一个非阻塞队列,当尝试向队列添加新元素并且队列已满时,它会自动从队列头部驱逐元素

// Create an EvictingQueue with a max size of 5
Collection<Integer> collection = EvictingQueue.create(5);
// Add 5 elements to the queue
collection.addAll(Arrays.asList(1, 2, 3, 4, 5));
System.out.println(collection);
// Add one more element
collection.add(6);
System.out.println(collection);

Output:输出:

[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]

just set the ith element to the ith+1 element and add the thing you want at the end:只需将第 i 个元素设置为第 i 个元素并在最后添加您想要的内容:

static int[] g(int arr[],int n){
    for(int i=0;i<arr.length-1;i++){
        arr[i]=arr[i+1];
    }
    arr[arr.length-1] = n;
    return arr;
}

public static void main(String [] args) {
    int[] arr = {1,2,3,4,5};
    System.out.println(Arrays.toString(g(arr,6)));
}

output:输出:

[2, 3, 4, 5, 6]

You might have to do something like:您可能必须执行以下操作:

public class Num {

    int[] array = {1,2,3,4,5};

    public void add(int number){
        int[] temp = array;
        array = new int[array.length];

        for(int i=1;i<temp.length;i++){
            array[i-1] = temp[i];
        }

        array[array.length-1] = number;

        for(int i=0;i<array.length;i++){
            System.out.print(array[i]+" ");
        }
        System.out.println();

    }

    public static void main(String[] args) {
        Num num = new Num();
        num.add(6);
        num.add(7);
        num.add(8);
    }
}

and output would look like this:输出将如下所示:

2 3 4 5 6 2 3 4 5 6
3 4 5 6 7 3 4 5 6 7
4 5 6 7 8 4 5 6 7 8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM