overexchange
overexchange

Reputation: 1

How do i avoid runtime type checks in this code?

As part of the assignment, I wrote the below code to encode the 2d-array into Doubly linked list.

RunLengthEncoding class takes care of encode/decode functionality. Amidst implementation of this class, there was a necessity to typecast some variables to push the type check(String) at runtime.

Below are the lines that does typecasting:

class RunLengthEncoding {
  private DList2 list;


  private String nextRun() {
      Object obj = null;
        .....
      obj = this.list.nTh(this.sizeOfRun);
      return (String)obj;
  }

  public void check() {
          ....
      while(node != this.list.sentinel){
         int nodetype = Utility.regexChecker("\\D{1,}", (String)node.runObject, 1);
      }
  }

}

====================

typecast is done because, because doubly linked list(class DList2{..}) is a list of DListNode2's which accepts and returns object of type Object.

class DListNode2{
   Object runObject;
   DListNode2 prev;
   DListNode2 next;
}

My question:

How should i avoid type casting in RunLengthEncoding class to avoid runtime type checks, when i use DList2 class?

Note: I am a java beginner.

Upvotes: 0

Views: 111

Answers (1)

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34776

You should use generics. For example:

class DList<T> {
    DListNode2<T> head; // Or whatever properties your class contains
}

class DListNode2<T> {
   T runObject;
   DListNode2<T> prev;
   DListNode2<T> next;
}

And in your RunLengthEncoding class declare list like this: DList<String> list;. That way you can define the type of the parameters in your list and won't have to do casting when you retrieve your object from the list.

Take a look at the standard Java Collections API classes, for example LinkedList. They do this the same way.

Upvotes: 1

Related Questions