Vector erzeugt neue Indizes nach Input

CortPoker

Aktives Mitglied
Hi zusammen,

bin gerade dabei, mittels Vector einen ADT Array nachzubasteln.
Soweit läuft es auch, allerdings habe ich das Problem, dass der Vector plötzlich mehr Indizes hat, als er laut Konstruktoraufruf überhaupt haben darf.
Und zwar wird jedes mal, wenn ich ein Element an irgendeinen Index hinzufüge, die Länge des Vectors um 1 erhöht.
Wieso?
Das index - 1 bei put und get steht da deswegen, weil dieser ADT bei Index 1 anfangen soll, ich aber den Index 0 nicht einfach nur als konstant "null" haben will.

Hier mal der wichtige Code:
Java:
public class Array<E> {

	private Vector<E> vec = null;
	private int lowerBound, upperBound, size;

	public Array(int lowerBound, int upperBound) {
		assert (lowerBound > 0 && lowerBound < upperBound) : "Untere Grenze muss größer oberer Grenze sein!";
		this.vec = new Vector<E>();
		this.lowerBound = lowerBound;
		this.upperBound = upperBound;
		for (int i = 0; i < upperBound; i++) {
			this.vec.add(i, null);
		}
		this.size = upperBound - lowerBound + 1;

	}

	public Array<E> put(E element, int index) {
		assert (this.lowerBound <= index && index <= upperBound) : "Index nicht vorhanden";
		this.vec.add(index - 1, element);
		return this;
	}

	public int lower() {
		return this.lowerBound;
	}

	public int upper() {
		return this.upperBound;
	}

	public E get(int index) {
		assert (this.lowerBound <= index && index <= upperBound) : "Index nicht vorhanden";
		return this.vec.get(index - 1);
	}

	public boolean empty() {
		return this.vec.isEmpty();
	}

	public String printArray() {
		return this.vec.toString();
	}

	public int getSize() {
		return size;
	}
}

Testklasse:
Java:
public static void main(String[] args) {
		Array<String> a = new Array<String>(1, 4);
		a.put("Stelle 1", 1);
		a.put("Stelle 2", 2);
		a.put("Stelle 4", 4);
//		a.put("Stelle 3", 3);
//		System.out.println(a.get(4));

		System.out.println(a.printArray());
		System.out.println(a.empty());
		System.out.println(a.getSize());
	}

Konsolenausgabe:
Java:
[Stelle 1, Stelle 2, null, Stelle 4, null, null, null]
false
4

bzw wenn ich nur Index 1 befülle:
Java:
[Stelle 1, null, null, null, null]

Wieso wird der Vector verlängert? Ich sehs nicht

Besten Gruß
 
weil das genau die Funktion von add ist?!

public void add(int index, E element)

Inserts the specified element at the specified position in this Vector. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

im Gegensatz zu

public E set(int index, E element)

Replaces the element at the specified position in this Vector with the specified element.
Vector (Java Platform SE 6)
 
Oh man, tatsächlich die Methoden durcheinander gebracht, da hätte ein Blick in die API ja schon geholfen.
Danke für den Nachhilfeunterricht 😀
 

Neue Themen


Zurück
Oben