Drago Drago - 2 months ago 25
Java Question

How can I change the instance the variable is pointing too?

Deque<String> d = new Deque<String>();


I want to change that later in the code to something like:

d = new Deque<Integer>();


Whenever I do it like that I get:

incompatible types Deque<Integer> cannot be converted to Deque<String>


How can I make it work, so I can assign
d
to
Deque<Integer>
?

I'm trying to accomplish the following:

Deque<String> d = new Deque<String>();
d.pushLeft("Datastructuren");
d.pushLeft("is");
d.pushRight("heel");
d.pushRight("leuk");
d.pushLeft("of");
d.pushRight("niet?");
d.changeLeft(5, "test");
d.changeRight(3, "een");
d.changeLeft(2, "Dit");
d.changeRight(4, "is");
d.popRight();
d.popLeft();

for (String i : d) {
System.out.print(i + " ");
}

d = new Deque<Integer>();
d.pushLeft(67);
d.pushLeft(1);
d.pushLeft(13);
d.pushRight(18);
d.pushRight(10);
d.pushRight(2);
d.pushLeft(29);
d.pushRight(88);
d.changeLeft(5, 25);
d.changeRight(1, 17);
d.popRight();
d.changeLeft(8, 18);
d.changeRight(5, 19);
d.popLeft();

for (int i : d) {
System.out.print(i + " ");
}


I know I can make a different variable but I was just curious if I could change the current
d
variable so it would use
Deque<Integer>
.

Answer

You should not try to give a (useless) solution to a question asking for something a programming language is not made for. In this case the answer is simply No way!

The real question is: Why do you want to do so?

  • Instead you can simply use another variable.
  • If you just want to fill the queue type safe but read regardless of the type you can refactor like below

At the end it is not really clear what you want to do with this code. If it just learning how a Deque works than a 2nd variable would do the job best. If not, refactoring would be an idea and maybe generic methods would help in processing the queue later.

Deque<?> d = fillWithString();

for (Object i : d) {
    System.out.print(i + " ");
}

d = fillWithInt();

for (Object i : d) {
    System.out.print(i + " ");
}

private Deque<String> fillWithString() {
  Deque<String> d = new Deque<String>();
  d.pushLeft("Datastructuren");
  d.pushLeft("is");
  d.pushRight("heel");
  d.pushRight("leuk");
  d.pushLeft("of");
  d.pushRight("niet?");
  d.changeLeft(5, "test");
  d.changeRight(3, "een");
  d.changeLeft(2, "Dit");
  d.changeRight(4, "is");
  d.popRight();
  d.popLeft();
  return d;
}

private Deque<Integer> fillWithInt() {
  Deque<Integer> d = new Deque<Integer>();
  d.pushLeft(67);
  d.pushLeft(1);
  d.pushLeft(13);
  d.pushRight(18);
  d.pushRight(10);
  d.pushRight(2);
  d.pushLeft(29);
  d.pushRight(88);
  d.changeLeft(5, 25);
  d.changeRight(1, 17);
  d.popRight();
  d.changeLeft(8, 18);
  d.changeRight(5, 19);
  d.popLeft();
  return d;
}

You cannot add or replace elements in d outside the fill methods in this refactoring as the compiler cannot check the type any more.

Comments