igonejack
igonejack

Reputation: 2532

How to make a Java array behave like a JavaScript array?

In JavaScript, I can write code like this:

var a = new Array();
a[2] = 'a';
a[20] = 'b';

and this would not work on Java, the point is I don't want to specific the exact length for it.

How could I keep this happy style when writing java?

Upvotes: 0

Views: 548

Answers (8)

dhalfageme
dhalfageme

Reputation: 1545

It depends, if you are going to use an array of a fixed size you can use:

char myarray[]=new char[50];
myarray[2]='a';
myarray[20]='b';

If you are going to change the size of the array dynamically you can use a Collection like an ArrayList (look at the doc) and insert chars in the positions you want

Upvotes: 0

tucuxi
tucuxi

Reputation: 17945

You can always write your own. You will not get the syntax, but most of the flavor will still be there.

Note that, efficiency-wise, this is a terrible idea. You can write much better code by learning "the Java way" of doing things. This is true of all languages: programming against the grain of the language is sure to cause you pain.

But here is the code:

class MyArray<T> extends ArrayList<T> {
    public MyArray<T>() { super(); }
    public void add(int i, T value) { 
        if (size() < i) { 
            ensureCapacity(i+1); // grow at most once instead of multiple times 
            while (size() < i)) { 
                add(null); // extend with a null object
            }
            add(value);
        } else {
            add(i, value);
        }
    }            
}

Now you can compare a garden-variety ArrayList with an instance of MyArray:

ArrayList<Character> a = new ArrayList<>();
MyArray<Character> b = new MyArray<>()
a.add(10, 'X'); // IndexOutOfBoundsException, size is 0
b.add(10, 'X'); // no exception - you get [10 x null, 'X']
b.get(10);      // returns 'X'

Bear in mind that JavaScript arrays can be indexed by arbitrary objects and not only integers -- but that the JavaScript VM tries to use numerically-indexed arrays if at all possible. For arbitrary indexing, you would need to use a Java HashMap:

class MyArray2<T> extends HashMap<Object, T> {
    public MyArray2<T>() { super(); }
    public void add(Object o, T value) { set(o, value); }
}

You would then use as:

MyArray2<Character> c = new MyArray2<>()
c.add("anything", '?');
c.get("anything"); // returns '?'

Upvotes: 0

xmoex
xmoex

Reputation: 2702

As others already pointed out: Java and JavaScript are two different things. For containers with variable size there is the Java collections framework.

But wich to choose? That depends on what you need. From your question I can imagine two cases:

a variable sized, indexed container:

basically an array-like list. In Java there's besides other list implementations the ArrayList used as follows:

List<Character> myList = new ArrayList<Character>(); 

// insert element at the end of the list
myList.add('a');

// insert element at specific position in list
myList.add(1, 'b');

// this will fail, because there's no element at position 2!!!
myList.add(3, 'c')

a container for mappings from integer to character:

In java there's lots of map implementations, I propose the HashMap, used like this:

Map<Integer,Character> myMap = new HashMap<Integer,Character>(); 

// insert mappings int -> char
myMap.put(0, 'a');
myMap.put(1, 'b');
myMap.put(20, 'c');

Each Container serves a different purpose. I advise reading the Java collections tutorial to be able to choose the best fitting one. Also take a look at tucuxi's answer, as he presented a solution wich simulates the desired beahviour but consider that (as he said himself) this is not the java way of doing things!

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

Java and JavaScript are two deferent languages. you can't do same thing in both

In Java you can write

char[] arr=new char[2];
arr[0]='a';
arr[1]='b';

If you don't want to specific the length, you can use List in Java

List<Character> list=new ArrayList<>();
list.add('a');
list.add('b');

Upvotes: 0

Boris the Spider
Boris the Spider

Reputation: 61158

You cannot. Java is to Javascript as ham is to hamster. There is no reason to believe they have the same syntax.

If you want a sparse array, use a Map:

final Map<Integer, Character> a = new LinkedHashMap<>();
a.put(2, 'a');
a.put(20, 'b');

Upvotes: 1

nobalG
nobalG

Reputation: 4620

like this

char arr[]=new char[30]; //declares an array which can hold 30 characters
    arr[2]='a';
    arr[20]='b';

but if you don't want to specify the length,than arraylist is something which will help you to accomplish your task because array's size is always fixed in Java

Upvotes: -1

user3655884
user3655884

Reputation: 159

If you don't want to specific length you can use List like this:

List<Character> list = new ArrayList<>();
list.add('a');
list.add('b');

Upvotes: 1

wonderbummer
wonderbummer

Reputation: 477

When you want an array of characters you can do it like this:

char[] array = new char[30];
array[2] = 'a';
array[20] = 'b';

Upvotes: 0

Related Questions