Skip to main content
GameDev.net gamedev.net
🔒 Locked

Question about casting in Java

Started by JC10001 Apr 10, 2002 at 2:15 PM 3 replies 150+ views
Original Post
JC10001
JC10001
Hi there, I am working on my very first java programs right now. They are a very basic chat server and client that run over telnet. I am getting a very strange error when I compile and I am hoping someone here might be able to help. In the server class I have declared a vector like so... Vector clientPorts = new Vector(); I am adding items to it like so.... clientPorts.addElement(new Integer(port)); Later in the program I am sending packets to everyone in the chat room, one at a time, by accessing each element of the vector to get the port number. I also have another vector which stores the IP address and I have successfully casted that one. Here is the function call... DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, (InetAddress)clientIPs.elementAt(i), (int[])clientPorts.elementAt(i)); I have also tried casting it as just plain (int) and (Integer) but I still get an error saying... UDPServer.java:103: Incompatible type for constructor. Can''t convert int[] to int. If I dont cast the vector element at all I get a msg saying that I have to cast it. Again, if anyone can help I will be sooo thankful. I just bought a book to learn java (its called On to Java) and I am following by the examples but for some reason this isnt working. This is very frustrating because I can''t get the vectors to work in java but I use them all the time in c++. Take care, JC
rickcheney
rickcheney
Yer, I don''t tend to use the Integer class as more often than not it causes problems.

The Integer class has a static function - intValue - which takes a Integer and returns an int. Use it to convert between them.

Try this:

Replace "(int[])clientPorts.elementAt(i)" with:
"Integer.intValue((Integer)clientPorts.elementAt(i)"

and all will be well.

Hope it helps.
rickcheney
rickcheney
oh, and close the brackets! sorry.
JC10001
JC10001
Hi,

Thanks. I did this and got it to compile.

(int)((Integer)clientPorts.elementAt(i)).intValue();

JC
HenryApe
HenryApe
You don't need the "(int)" in front of the statement. The intValue method of the Integer class returns an int so no need to cast that.

[edited by - HenryAPe on April 10, 2002 4:39:41 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.