What is the Equivalent code From array_push in java?

2.1k Views Asked by At

Hi guys I need the equivalent java code of this PHP code:

<?php
  $stack = array("orange", "banana");
  array_push($stack, "apple", "raspberry");
  print_r($stack);
?>

the Output is:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
3

There are 3 best solutions below

1
On BEST ANSWER

You have to use a ArrayList.

List<String> list = new ArrayList<String>();
list.add("orange");
list.add("banana");
0
On

That would be add(Element) method for an ArrayList.

For an array, you have to manually say at which index, what element:

String[] word = new String[5];
word[4] = "raspberry";

Or

String[] word = {"orange","banana","raspberry","srtrawberry"};
1
On

This would be a close equivalent:

import java.util.*;

List stack = new ArrayList(Arrays.asList("orange", "banana"));
Collections.addAll(stack, "apple", "raspberry");
System.out.println(stack);