3

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
)
Ry-
  • 218,210
  • 55
  • 464
  • 476

3 Answers3

4

You have to use a ArrayList.

List<String> list = new ArrayList<String>();
list.add("orange");
list.add("banana");
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
0

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"};
Mechkov
  • 4,294
  • 1
  • 17
  • 25
0

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);
ataylor
  • 64,891
  • 24
  • 161
  • 189
  • You will get ConcurrentModificationException when trying to add elements to your stack as Arrays.asList() returns unmodifieable Arrayl.ArrayList, not regular java.util.ArrayList. In this situation you should use List stack = new ArrayList(Arrays.asList("orange", "banana")); – Artem Jan 06 '12 at 21:00