Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Type of object?

Name: Anonymous 2010-04-01 11:15

Sup /prog/riders?

I have a common problem (I guess).
I have an abstract class "X" and two classes ("A" and "B") that inherit from it. Also I really need a list that can handle both of them.

List<X> mylist;
mylist.add(A);
mylist.add(B);

Now I need to pick out all items of type A and do something with them, possibly using methods only available in class A and NOT in X or B. In ENTERPRISE JAVA there is "instanceof" but using that sounds just as hacky as saving a type in every object.


Is there a CLEAN way of determining if the object from the X-list is of type A?
Not Java-specific, rather OOP in general.

Name: Anonymous 2010-04-01 12:19

>>12
#include <stdio.h>
#include <sys/times.h>

struct _o {
 int type;
 int i;
} o[1024];

int main() {
 int i,j;
 clock_t time_1;
 struct tms time_s;
 for(i=0;i<1024;i++) {
  o[i].type=rand()&1;
  o[i].i=rand();
 }
 time_1 = times(&time_s);
 for(i=0;i<1048576;i++) {
  for(j=0;j<1024;j++) {
   if(o[j].type)
    o[j].i--;
   else
    o[j].i++;
  }
 }
 printf("Took %d ticks\n",times(&time_s)-time_1);
 return 0;
}


Took 420 ticks

#include <stdio.h>
#include <sys/times.h>

struct _o {
 int (*gettype)();
 int i;
} o[1024];

int gettype_a() {
 return 0;
}

int gettype_b() {
 return 1;
}

int main() {
 int i,j;
 clock_t time_1;
 struct tms time_s;
 for(i=0;i<1024;i++) {
  o[i].gettype=rand()&1?gettype_a:gettype_b;
  o[i].i=rand();
 }
 time_1 = times(&time_s);
 for(i=0;i<1048576;i++) {
  for(j=0;j<1024;j++) {
   if(o[j].gettype())
    o[j].i--;
   else
    o[j].i++;
  }
 }
 printf("Took %d ticks\n",times(&time_s)-time_1);
 return 0;
}


Took 670 ticks

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List