Reducing casting by using toString()

JAVA

    Sponsored Links

    Next

  • 1. How to get the instantiated object behind an interface
    Hello, Lets say I had the following: an interface called GMike Then I have a class: public void bsd_mike extends Button implements GMike { } In my program I have: GMike mike; mike = getthemike(); getthemike gives me a bsd_mike object. I want to be able to do a: pannel.add(mike); However the add method in panel does not care for mike being a GMike. I have created a method in GMike public Component getSelf() { return(this); } and then I do: panel.add(mike.getSelf()); and that works. Is there a better way though?? Is there an existing method that does what getSelf does? Thank you, Mike
  • 2. Obtain file path and file name using file chooser
    Hi All, I want to obtain both file "path" and the filenamed MyText.txt ....as in "C:\Documents and Settings\bH\Desktop\MyShowWithFrame\MyText.txt" I have tried to discover the options shown in How to Use File Choosers (The JavaTutorials Creating a GUI with JFC-Swing Using Swing Components).htm I cannot understand what options should be shown as but this does not work. Program snip: JButton opnButton = new JButton("Open a Text File..."); buttonPanel.add(opnButton); opnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile (); strngFileName = file.getName(); } } }); }); TIA bH
  • 3. CheckBox in a ListCellRenderer
    Hi, I've implemented a ListCellRenderer panel, that contains among other components a JCheckBox to visualise the 'selected' state of the elements in a JList object. I'm wondering if there is a way to directly change the selection state of the checkbox using the mouse. As the list is implemented now, a mouse click just selects the list element itself, but I've found no way yet to directly change the state of the checkbox. I could add a MouseListener to the list and process a double click to alter the checkbox, but I'm wondering if there is a better way using a single mouseclick. Thanks in advance. -- Luc Van Bogaert
  • 4. Help with : send "hello world" ASCII text to Linux serial port and read into a text file in java virtual machine...
    Hello. Excuse the fact that I'm a newbie. I have a linux v 2.4 box with serial port something like ttyS0. I have a java VM running. I want to be able to pass the phrase"hello world" that is sent to the serial port with hyperterminal from a PC to a .java program running inside java virtual machine. I'm not sure if I'm on the right track with: FileInputStream, fis read() I guess the idea is to read 1 character at a time and build up a file like textfile.txt I can only use printable characters. Maybe I need some flags like: start_of_text and end_of_text are needed? I just want to able to read the text file after it has been sent, and the "hello world" is now there! Any help with this would be greatly appreciated!!! Thanks in advance.

Reducing casting by using toString()

Postby rob-cop » Wed, 26 May 2004 02:09:20 GMT

Is it possible to reduce casting by toString() method?

eg. *VendingMachine class uses ItemType class*

public class VendingMachine{

public VendingMachine{ }

if(inputamount < ((ItemType)list.get(i)).getName())
                 |________________________________|

ArrayList list = new ArrayList(); //collection of object reference of ItemType

}

VendingMachine maintains the collection of ItemType objects.

How can I reduce the above expression by using toString()?
_______________________________________________________________________________

Thank you very much for any help!

Re: Reducing casting by using toString()

Postby Murray » Wed, 26 May 2004 02:41:08 GMT





ItemType
____________________________________________________________________________
___

Your code is a bit confusing ..

inputamount is a number I assume, and getName() looks like it would be a
String? And you're using < ? *confused*

Disregarding that, I guess you could technically use toString() to avoid a
cast, but that's not what it's designed for. In your example above, you
could make your toString() return getName(), then you could do
list.get(i).toString() without having to cast to ItemType. But I would never
do that.

What's wrong with casting anyway? Apart from it looking a bit ugly. Maybe
you should wait for Java 1.5 Generics :-)



Re: Reducing casting by using toString()

Postby Murray » Wed, 26 May 2004 02:41:51 GMT





ItemType
____________________________________________________________________________
___

Your code is a bit confusing ..

inputamount is a number I assume, and getName() looks like it would be a
String? And you're using < ? *confused*

Disregarding that, I guess you could technically use toString() to avoid a
cast, but that's not what it's designed for. In your example above, you
could make your toString() return getName(), then you could do
list.get(i).toString() without having to cast to ItemType. But I would never
do that.

What's wrong with casting anyway? Apart from it looking a bit ugly. Maybe
you should wait for Java 1.5 Generics :-)




Re: Reducing casting by using toString()

Postby Eric » Wed, 26 May 2004 07:38:49 GMT





ItemType
____________________________________________________________________________
___

When you toString() a  Collection (e.g., ArrayList), it will apply invoke
each object's toString() as follows: [name1, name2, ...]. Not very useful
for a comparison though. Live with the cast (at least until 1.5 is part of
normal life) to get what you need (lots of IDE's will even help you generate
it with minimal typing).

Hope that helps, -Eric



Re: Reducing casting by using toString()

Postby Woebegone » Sun, 30 May 2004 12:28:12 GMT

ItemType
____________________________________________________________________________
___

As the previous posters pointed out, toString probably isn't what you want.
If you're determined to use your list like an array, the following will
create an array from your list with the correct type:
ItemType[] items = (ItemType[])list.toArray(new ItemType[list.size()]);

Now, you can write code like "items[i].getName()" if you prefer. There's a
cost to doing it this way though.

-- 

Sean.



Re: Reducing casting by using toString()

Postby Woebegone » Sun, 30 May 2004 12:44:21 GMT




ItemType
____________________________________________________________________________
___

Another possibility is to implement a class that uses the list but
simplifies the interface. If you know that it only ever will hold ItemTypes,
make an ItemTypeList, something like the example below (this is more work in
the short run, but could save a lot of grief over a large system).
Basically, write an adapter for the list so that all you can ever do is
add/remove/etc. ItemTypes. Then give some methods like "getNameAt(int)" so
you don't have to "get(i).getName()" (assuming this is a common operation -- 
the one you wanted to streamline the call to).

Finally, you could provide a custom iterator that wraps an Iterator from the
item list but returns ItemTypes with no casting. There's some overhead cost,
but then using the thing is much easier.

HTH! Regards,
Sean

<code>
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


interface ItemType {
  public String getName();
  public double getPrice();
}

class ItemTypeList {
  private List list;
  public ItemTypeList() {
    list = new ArrayList();
  }
  public boolean add(ItemType item) {
    return list.add(item);
  }
  public String getNameAt(int i) {
    return get(i).getName();
  }
  public ItemType get(int i) {
    return (ItemType)list.get(i);
  }
  public ItemTypeIterator iterator() {
    return new ItemTypeIterator(list.iterator());
  }
}

class ItemTypeIterator {
  private Iterator iterator;
  public ItemTypeIterator(Iterator iterator) {
    this.iterator = iterator;
  }
  public boolean hasNext() {
    return iterator.hasNext();
  }
  public ItemType next() {
    return (ItemType)iterator.next();
  }
}

public class VendingMachine {
  private ItemTypeList items;
  public ItemType buy(String name, double amount) {
    ItemTypeIterator i = items.iterator();
    while (i.hasNext()) {
      ItemType item = i.next();
      if (item.getName().equals(name)) {
        if (item.getPrice() <= amount) {
          return item;
        }
        else {
          // throw too little money exception
        }
      }
    }
    // should throw sold out exception
    // instead just return null for e.g.
    return null;
  }
}

</code>



Re: Reducing casting by using toString()

Postby Quec » Sun, 30 May 2004 20:00:48 GMT

Maybe I am wrong but ,

class ItemTypeList {

should implements the  interface ItemType... ?

The newbe.



Re: Reducing casting by using toString()

Postby Woebegone » Sun, 30 May 2004 22:07:41 GMT





In a more sophisticated context you might want something like that, but it
would imply the possibility of a recursive relationship where each list item
might be an ItemType _or_ an ItemLypeList. For this example, I really just
wanted to demonstrate how encapsulation could simplify use of the
Collection.

I think that what you 're describing is the "Composite" design pattern -- 
more than the example called for.

Or, do you mean because I provide no implementation of ItemType? I used only
an interface for ItemType because it's implementation doesn't matter for
this example, and would just have been extra baggage. To actually use the
code would require a concrete ItemType though, you're right. I'm assuming
the OP has one already to plug in. :-)

-- 
Thanks,
Sean.


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system ( http://www.**--****.com/ ).
Version: 6.0.690 / Virus Database: 451 - Release Date: 22/05/04



Similar Threads:

1.Which of these is better casting or toString()

 List lst = new ArrayList();
  lst.add("a");
// more add statements here..

((String) lst.get(j)).toUpperCase()

 lst.get(j).toString().toUpperCase();

casting  or toString() ?? which one is better to use.

kiri

2.difference between toString() and type casting a n Object to String

what is the difference between toString() and type casting a n Object
to String

3.using ClassDep to reduce rt.jar

i have been trying to use the JINI tool ClassDep to create a list of the 
dependencies of a program i have written, but have been unsuccessful.  when 
i run it i output a list of classes that ClassDeps says my program needs, 
but when i create an rt.jar file containing only those classes (yes, in the 
appropriate package directories) i get the following:
NoClassDefFoundError: java.lang.ArrayStoreException.

i figured maybe it was a fluke, and just manually included the class.
after doing so i got the following, more confusing error:
error: java.lang.Error: java.io.UnsupportedEncodingException: Cp1252 

Cp1252 is not something i specifically make reference to in my program, and  
have only a nebulous idea of what it even is/does.

anyway, though, that's beside the point:  i would really like to make a 
slimmed down version of rt.jar to fit my specific needs according to the 
classes that are needed by my app.

is there any way to do this that works, or am i just using ClassDep 
incorrectly?

Please Help!
Thank You!
-Voltaic

4.Another question about inheritance (up-casting and down-casting)

Hi all:

Sorry to bother you again:)

Still the question about inheritance,please see this codes below
first:

// codes start
class base{//a base class
    
    // constructor
    public base(){
	System.out.println("base class construct");
    }
    // perform
    public void perform(){
	System.out.println("base class perform");
    }
    // destructor
    public void finalize(){
	System.out.println("base class destruct");
    }
}


class subbase extends base{// derive from base
    
    // constructor
    public subbase(){
	System.out.println("sub class construct");
    }
    // perform
    public void perform(){
	System.out.println("sub class perform");
    }
    // destructor
    public void finalize(){
	System.out.println("sub class destruct");
    }
}

public class casting{// test casting class
    // constructor
    public casting(){
	System.out.println("begin casting test");
    }

    public static void main(String args[]){
	base father = new base();
	subbase son = new subbase();
	
	father.perform();
	son.perform();

	father = (base)son;      //          <1>
	father.perform();         

	son = (subbase)father;   //          <2>
	son.perform();

	father = (base)((subbase)father);   //   <3>
	father.perform();
    }
}

// codes end

***************************************************
and the execution result is:
// begin
base class construct
base class construct
sub class construct
base class perform
sub class perform
sub class perform                // <a>
sub class perform                // <b>
sub class perform                // <c>
// end

****************************************************

My question is: there are 3 castings in the codes(e.g. <1><2><3>),but
why they perform not as I like, I cast the subclass son to base class
at <1>, but at <a>,father.perform() don't print "base class perform",
the situation is similar in <2><a> and <3><c>,so, why?


****************************************************
And I am confused about how "casting" behave?
for example:

base class:                          sub class derive from base
+---------------+                    +------------------------------+
| int nbase     |                    | int nbase   int nsub         |
-----------------                    --------------------------------
| void fbase()  |                    | void fbase() void fsub()     |
+---------------+                    +------------------------------+

so, if I declare:

base a = new base();  // a should contains nbase and fbase()
sub  b = new sub();   // b should contains nbase,nsub and
fbase(),fsub()
base c;
sub  d;

c = (base)b;  //   ? what c contains ?  like a or like b
              //   that is to say if son class upcasting to father
class
              //   if the member belongs to son class should be
truncated?
d = (sub)c;   //   ? what d contains ?  like a or like b
              //   that is to say if d get the members belongs to son
class
              //   automatically
// d == b ? i mean if equal in memory profile

*******************************************************

I am a little confused about how memory allocation changes when
upcasting
or downcasting ?



that's all

thank you!


kevin

5.Restricting package access when using reflection/casting

Here's a scenario.. I have the following interface:

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

package com.mypublicpackage;

public interface MyInterface {
	public void foo();
}

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

and the following class:

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

package com.myprivatepackage;

public class MyClass implements com.mypublicpackage.MyInterface {
    public void foo() {}
    public void bar() {}
}

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

I have a method in another class that returns a reference to
MyInterface, eg:

package com.mypublicpackage;

public class MyImplementation {
    public MyInterface getMyInterface() { return new
com.myprivatepackage.MyClass(); }
}

I want to protect applications (loaded with my class loader) from
accessing anything directly in com.myprivatepackage. So if I call
MyImplementation.getMyInterface() then I should NOT be able to cast
MyInterface to MyClass or use reflection to call MyClass.bar() without
getting an AccessControlException etc.

I have my own SecurityManager and Policy implementation so is it just a
question of adding "com.myprivatepackage." to the package.access line
in java.security or is there more to it than that?

Thanks,

Stu

6. Getting class using (Class.forname()) and casting the instance

7. How to reduce startup latency while playing .wmv file - from Javas

8. Tuning a machine to reduce run time.



Return to JAVA

 

Who is online

Users browsing this forum: No registered users and 56 guest