| Newbie Question - ArrayLists and methods |
|
 |
Index ‹ java-programmer
|
- Previous
- 1
- java.sql.SQLException: Io exception: The Network Adapter could not establish the Hi,
I am sridhar, i have Oracle 10g express on my machine , when i am
trying to connect to Database via java jdbcAPI using Thin Driver , i
am getting the following Exception:
java.sql.SQLException: Io exception: The Network Adapter
could not establish the connection.
How can i resolve this problem,can any one give me the appropriate
solution.
Thanks
Sridhar
- 1
- c prog socket connect to java programmy c program wants to send a message to java program through socket.
The problem i have is the message received by java socket server
is not a complete message most of time. Please see my attachment of
c prog and java program.
Thank you very much for your kind help.
Mei
Here is my c client program:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc,char **argv) {
FILE *fileIn; /* declare a FILE pointer */
FILE *fileOut; /* declare a FILE pointer */
char buffer[8000];
char line[4000];
char c;
int create_socket;
int bufsize = 1024;
int len=0;
int cnt=0;
char *cmd = "XML2Marc,/export/home/mml/Marc4jProg/Marc4jTest/testcase/exporttsamnonowner5.xsl,MARC8,";
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
fileOut = fopen("data/out.xml", "w");
if(fileIn==NULL) {
printf("Error: can't open file.\n");
return 1;
}
else {
strcat(buffer,cmd);
if ( (fileIn = fopen("data/test.xml", "r")) != NULL) {
fgets(line, sizeof(line), fileIn);
}
fclose(fileIn);
strcat(buffer,line);
strcat(buffer,"\r\n");
len= strlen(line);
printf("debug::buffer:: %d \n %s", len, buffer);
fprintf(fileOut,"%s", buffer);
portno = 5088;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("hopper2.rlg.org");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
n = write(sockfd,buffer,strlen(buffer));
sleep(20);
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,4000);
printf(" test ");
n = read(sockfd,buffer,4000);
if (n < 0)
error("ERROR reading from socket");
printf("output::: %s\n",buffer);
printf("%d",n);
if(strlen(buffer)<2){ //try another time
n = read(sockfd,buffer,4000);
if (n < 0)
error("ERROR reading from socket");
printf("output::: %s\n",buffer);
}
printf("File opened. Now closing it...\n");
fclose(fileIn);
fclose(fileOut);
return 0;
}
}
and here is the partial java program:
public class Marc4jWorker extends Thread{
....
public void run(){
char[] ln=new char[8000];
OutputStream outbound=null;
InputStream inbound =null;
while(true){
String line="";
int cc=0;
String action= null;
String style=null;
String encode="UTF8";
String xmlstr=null;
//String line;
try{
inbound = client.getInputStream();
int btecnt = inbound.available();
byte[] bf=null;
if(btecnt<=0)
continue;
else {
bf = new byte[btecnt];
inbound.read(bf);
}
//why the message is incomplete ????
System.out.println("server: input bytes length:"+bf.length);
line =new String(bf);
if(Config.ENDREQ.equalsIgnoreCase(line)){
outbound.close();
client.close();
System.err.println("request end");
break;
}
//line = bf.toString(Config.ENC_UTF8);
int ps_firstcomma =line.indexOf(',',0);
int ps_secondcomma = 0;
int sz=line.length();
if(ps_firstcomma>0 && ps_firstcomma<sz-1)
action=line.substring(0,ps_firstcomma).trim();
ps_secondcomma=line.indexOf(',',ps_firstcomma+1);
if(ps_firstcomma<ps_secondcomma && ps_secondcomma>0 &&
ps_secondcomma<sz-1)
style=line.substring(ps_firstcomma+1,ps_secondcomma).trim();
ps_firstcomma=ps_secondcomma+1;
ps_secondcomma=line.indexOf(',',ps_firstcomma+1);
if(ps_secondcomma>0 && ps_secondcomma<sz-1){
encode=line.substring(ps_firstcomma,ps_secondcomma).trim();
Log.println("server encode:"+encode);
//for action is xml2marc, input xml encoding is always UTF8
if(action.equalsIgnoreCase("xml2marc")){
xmlstr= new
String(bf,Config.ENC_UTF8).substring(ps_secondcomma+1);
}else if("marc2xml".equalsIgnoreCase(action)){
if(Config.ENC_UTF8.equalsIgnoreCase(encode))
xmlstr= new
String(bf,Config.ENC_UTF8).substring(ps_secondcomma+1);
else
xmlstr= new
String(bf,Config.ENC_ISO).substring(ps_secondcomma+1);
}else{
System.out.println("Unsupported Action!");
continue;
}
}
FileOutputStream fout =null;
String rs = null;
if(action.equalsIgnoreCase("xml2marc")){
if(Config.ENC_UTF8.equalsIgnoreCase(encode)){
fout = new FileOutputStream("/tmp/servertest.input",true);
fout.write(xmlstr.getBytes(Config.ENC_UTF8));
fout.close();
}
else {
fout = new FileOutputStream("/tmp/servertest.input",true);
fout.write(xmlstr.getBytes(Config.ENC_ISO));
fout.close();
}
rs = Xml2Marc.toMarc(style,encode,xmlstr);
}else if(action.equalsIgnoreCase("marc2xml")){
if(Config.ENC_UTF8.equalsIgnoreCase(encode)){
fout = new FileOutputStream("/tmp/servertest.input",true);
fout.write(xmlstr.getBytes(Config.ENC_UTF8));
fout.close();
}
else {
fout = new FileOutputStream("/tmp/servertest.input",true);
fout.write(xmlstr.getBytes(Config.ENC_ISO));
fout.close();
}
rs = Marc2Xml.toXML(style,encode,xmlstr);
}
fout = new FileOutputStream("/tmp/servertest.output");
outbound =client.getOutputStream();
if(rs==null || rs.length()==0)
rs="00005";
if("Xml2Marc".equalsIgnoreCase(action)){
if(encode.equalsIgnoreCase(Config.ENC_UTF8)){
outbound.write(rs.getBytes(Config.ENC_UTF8));
fout.write(rs.getBytes(Config.ENC_UTF8));
}else{
fout.write(rs.getBytes(Config.ENC_ISO));
outbound.write(rs.getBytes(Config.ENC_ISO));
}
}else if("Marc2Xml".equalsIgnoreCase(action)){
outbound.write(rs.getBytes(Config.ENC_UTF8));
fout.write(rs.getBytes(Config.ENC_UTF8));
}
outbound.flush();
fout.close();
} catch (IOException e) {
Log.println("Read failed"+e.toString());
System.exit(-1);
}catch(Exception e){
Log.println("server error:"+e.toString());
}
}
}
- 3
- J2EE programming on very old computerHi
I've old computer (Celeron 300 HHz, 64 RAM, WIN98)
Cold You say me, which app I need to start learn Java (J2EE) on this computer.
Best regards
Krzysztof
- 3
- Struts, Spring, ... what about Swing?So many Web frameworkings seem to have sprung up but are there any
really good frameworks for fat clients using things like Swing?
I am most interested in how the server side objects interact with Swing
components, the design patterns behing client/middleware/server/db apps
etc.
thanks
Tim
- 4
- javaw.exe - Xrs -jar my.jarAs I understand when Java program started this way it should ignore user
logoff
and continue working but it doesent for me :(
I run my application from cmd on WinXP like this :
javaw.exe - Xrs -jar my.jar
When I logoff from system application exits , what I'am doing wrong ?
regards,
Os
- 4
- Regex syntaxI have managed to form the regex for the following two:
CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
String CTL_REGEX = "([[\\x00-\\x1F]\\x7F])";
LWS = [CRLF] 1*( SP | HT )
String LWS_REGEX = "((\r\n)??( |\\x09)+?)";
However, the following stumped me for hours.
TEXT = <any OCTET except CTLs, but including LWS>
String TEXT_REGEX = ...... // help me out please.
- 11
- Eclipse won't startHi
I have just installed eclipse-2.1.1_2 on my FreeBSD 4.8 computer.
When I try to run it I get:
java.lang.UnsatisfiedLinkError:
/usr/local/eclipse/plugins/org.eclipse.swt.gtk_2.1.1/os/freebsd/x86/lib
swt-pi-gtk-2135.so: /usr/local/lib/libgthread-2.0.so.200: Undefined
symbol "pthread_attr_destroy"
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1382)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1290)
at java.lang.Runtime.loadLibrary0(Runtime.java:749)
at java.lang.System.loadLibrary(System.java:820)
at org.eclipse.swt.internal.Library.loadLibrary(Library.java:108)
at org.eclipse.swt.internal.gtk.OS.<clinit>(OS.java:18)
at org.eclipse.swt.widgets.Display.create(Display.java:469)
at org.eclipse.swt.graphics.Device.<init>(Device.java:111)
at org.eclipse.swt.widgets.Display.<init>(Display.java:303)
at org.eclipse.swt.widgets.Display.<init>(Display.java:299)
at org.eclipse.ui.internal.Workbench.run(Workbench.java:1361)
at
org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoade
r.java:858)
at org.eclipse.core.boot.BootLoader.run(BootLoader.java:468)
at java.lang.reflect.Method.invoke(Native Method)
at org.eclipse.core.launcher.Main.basicRun(Main.java:291)
at org.eclipse.core.launcher.Main.run(Main.java:747)
at org.eclipse.core.launcher.Main.main(Main.java:583)
(eclipse:9359): Gtk-WARNING **: Unable to locate theme engine in
module_path: "redmond95",
Btw I have heard Eclipse has a C++ plugin, would it be possible to get
that into the port collection?
br
socketd
_______________________________________________
email***@***.com mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-java
To unsubscribe, send any mail to "email***@***.com"
- 13
- converting between double and integerI have a variable declared as a double as :-
sValue = Math.floor(Math.sqrt(polynomialDegree));
where 'polynomialDegree' is an integer.
How do I convert 'sValue' to an integer?? I cant declare sValue as an
integer straight off because its returning an error message saying 'possible
loss of precision', and have tried to convert it to an integer using
intValue() but keep getting an error saying 'double cannot be dereferenced'
Where am i going wrong?
Thanks
- 14
- renameTo for Directories on SolarisI've been attempting to rename a directory on Solaris 8 and continue to
have problems.
I read other threads that mention it is not possible to do when moving
between partitions on Solaris, but I am renaming to the same
paritition.
I am basically attempting the following:
File oldName = new File("/opt/OldDirectoryName");
File newName = new File("/opt/NewDirectoryName");
if ( oldName.renameTo( newName ) )
// Successfully renamed
else
// Failed to rename
For some reason I seem to continually be unable to do this.
Any ideas?
Eric
- 14
- Which IDE to choose (more specific than earlier, very similar post)?Hello guys,
I'm C++/Windows programmer and I'd like to smoothly switch to Java. I read
replies to earlier, very similar post, but I didn't even hear about such
IDEs :-(
My question is following: using what IDE can I easily create applets with
controls like edit, list, combo boxes, buttons, tree controls and - this is
very important - have support to draw 3D graphics? Some time ago I was using
Borland JBuilder, but I guess it was not intended for building commercial
releases. I was browsing Sun Microsystems' site and found free "Sun Java
Studio Creator, Early Access". Can I create in it commercial applets using
features that I described above? If not, please advise me something free or
really good enough (read: easy to develop applets) to spend money IDE;
preferably free of course :-)
Generally I focused on "Sun Java Studio Creator, Early Access", but I'm
waiting for your replies.
Please reply, your opinion is crucial for me.
Regards
P.S. I'm not going to create server-side applets. I will be doing applets
run in web browser.
- 15
- Creating tiled image from multiple tiff sources in JAIHi all,
My situation is as follows. I have a number of tiff files containing
adjacent tiles which I would like to combine into one image. Currently I
achieve this goal in the following manner using the Java Advanced Imaging
library:
1) Create a target TiledImage with attributes appropriate to hold all tiles.
2) Load each tiff file into a separate PlanarImage.
3) Get the Rasters of each of these PlanarImages and translate coordinates
according to the rectangle they must occupy in the target TiledImage
4) Invoke TiledImage.setData(Raster) with the translated raster for each
tile
This works ok, but it does not seem to take advantage of the JAI's
pull-model; image data is loaded into memory immediately, probably as a
consequence of the call to getRaster(). However I wish to defer the loading
of image data into memory until it is needed, because only a subset of all
tiles are two be displayed at any one time.
I hence believe I need something along the lines of the NullOpImage class.
Unfortunately, the constructor for this class only takes a single source,
while I need to be able to pass a source for each tiff tile. One solution is
to subclass NullOpImage (or its superclass, PointOpImage) and take care of
things myself. Is this the way to go about it, or is there a better and
easier solution?
Any suggestions will be greatly appreciated.
Regards,
Michael.
- 15
- Socket functionality on jre 1.6.0 beta b59g
OK, it seems that on Windows XP Pro, that Socket has changed significantly,
breaking lots of my code.
Using "localhost" no longer appears to work to create a Socket object
on a port. Have to use "127.0.0.1" instead. Other aspects of Socket
also appear to be flaky/changed... I can certainly "ping localhost" so
it's not that localhost has a problem.
Can someone please explain the plain Socket changes for this new 1.6 ??
java version "1.6.0-beta"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.6.0-beta-b59g)
Java HotSpot(TM) Client VM (build 1.6.0-beta-b59g, mixed mode, sharing)
- 15
- How to detect existing text tables in a hsql db?I have a Java-Application that creates several text-tables at the first
start. When I start the application again I just want to check, if the
text tables exist. But the application always returns a "false, table
does not exist" and the localdb.properties and localdb.script files are
written new. After that, the tables can be detected, but only until the
next start of the application.
dbcon.connect(LOCALDRIVER, LOCALPROTOCOL, LOCALDATABASE, LOCALUSER,
LOCALPASS);
DatabaseMetaData metadata = dbcon.con.getMetaData();
String[] aTyps = new String[]{"TABLE"};
ResultSet result = metadata.getTables(null, null, "%", aTyps);
while (result.next()) {
System.out.println(result.getString("TABLE_NAME"));
}
result.close();
Susanne
- 15
- HELP needed: Small Java applet I need a graphic Java applet that makes the following steps:
Given a circumference of radius "r",
Draw onscreen, say, 20 random radius.
Then, every time you press a button:
Rotate the 20 radius a given random angle (same for everyone).
Draw the new radius onscreen.
Note: The radius endpoints should be stored in float arrays and drawn as
float. (Of course one of the endpoints of every radius would be the center
of the circumference.)
I'm not very good at Java at the moment but I'd like to transform an old
program from QBasic into a java applet and I think that this little
framework is all I need. What I am getting at the moment is a lot of
compilation errors I don't understand.
The program I want to transform is here:
http://www.josechu.com/moving_fractal/index.htm
Thanks,
Josechu
- 16
- client server communication in java I have a java web service that returns byte arrays to the client.
First a byte array is returned and the server gets the acknowledgement,
then the next byte array is sent and so on. But I don't have much idea
how to implement it. How can I resume from where I stopped at the
server side? Can anyone give me some idea so that I can proceed?
|
| Author |
Message |
Taria

|
Posted: 2007-11-11 18:46:00 |
Top |
java-programmer, Newbie Question - ArrayLists and methods
Hello all (again),
My problem here is that I'm trying to build a list of ArrayLists that
hold data and I want to add the newly derived data into a table where
it's dependent on the first row. A short version of my program to
illustrate what I mean:
import java.util.*;
public class MyProg2 {
public static void main(String[] args) {
List table = new ArrayList ();
List <Integer> data = new ArrayList <Integer>();
data.add(1);
data.add(3);
data.add(4);
table.add(data);
System.out.println ("table(0) = " + table.get(0));
ArrayList <Integer> newNode = new ArrayList <Integer>();
newNode = createNode((ArrayList)table.get(0),0);
table.add(newNode);
System.out.println ("Added in a new row and table is now:");
System.out.println ("table(0) = " + table.get(0));
System.out.println ("table(1) = " + table.get(1));
} //end main driver
public static ArrayList createNode(ArrayList items,int lParen){
int a = 0; int b=0; int c=0;
if (items.size() >= 2){
a = Integer.valueOf(items.get(lParen).toString());
b = Integer.valueOf(items.get(rParen).toString());
c = a + b;
items.remove(lParen);
items.remove(lParen);
items.add(lParen,c);
}
return items;
}
}
(I'm unable to get rid of all the unchecked msgs because putting the
<Integer> tag sometimes made the program uncompilable. Use --nowarn
when you compile this program. :)
Iin this code, row 0 of table is changed in the method while it
creates row 1, but I don't understand why and don't know how to keep
it from changing. From this behavior, it's leading me to believe
ArrayLists are passed by value or is this the way of ArrayLists? I
thought parameters were passed by reference? What am I missing here?
-t
|
| |
|
| |
 |
Joshua Cranmer

|
Posted: 2007-11-11 22:26:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Taria wrote:
> Hello all (again),
>
> My problem here is that I'm trying to build a list of ArrayLists that
> hold data and I want to add the newly derived data into a table where
> it's dependent on the first row. A short version of my program to
> illustrate what I mean:
>
> import java.util.*;
> public class MyProg2 {
> public static void main(String[] args) {
> List table = new ArrayList ();
List<List<Integer>> table = new ArrayList<List<Integer>>();
> List <Integer> data = new ArrayList <Integer>();
> data.add(1);
> data.add(3);
> data.add(4);
> table.add(data);
>
> System.out.println ("table(0) = " + table.get(0));
>
> ArrayList <Integer> newNode = new ArrayList <Integer>();
> newNode = createNode((ArrayList)table.get(0),0);
... so you can change this line to:
newNode = createNode(table.get(0),0);
> table.add(newNode);
> System.out.println ("Added in a new row and table is now:");
> System.out.println ("table(0) = " + table.get(0));
> System.out.println ("table(1) = " + table.get(1));
>
> } //end main driver
> public static ArrayList createNode(ArrayList items,int lParen){
public static List<Integer> createNode(List<Integer> items, int lParen){
> int a = 0; int b=0; int c=0;
> if (items.size() >= 2){
> a = Integer.valueOf(items.get(lParen).toString());
> b = Integer.valueOf(items.get(rParen).toString());
typo? I see no `rParen' defined anywhere.
> c = a + b;
> items.remove(lParen);
> items.remove(lParen);
> items.add(lParen,c);
> }
> return items;
> }
> }
Here is my rough estimate of what the second method should look like:
public static List<Integer> createNode(List<Integer> items,
int leftIndex, int rightIndex) {
// Create a copy so we can modify without changing...
items = new ArrayList<Integer>(items);
if (items.size() >= 2){
int sum = items.get(leftIndex)+items.get(rightIndex);
// Remove from the right first -- otherwise we're off by one.
items.remove(rightIndex);
items.remove(leftIndex);
items.add(leftIndex,sum);
}
return items;
}
> (I'm unable to get rid of all the unchecked msgs because putting the
> <Integer> tag sometimes made the program uncompilable. Use --nowarn
> when you compile this program. :)
Have you read up on generics?
> Iin this code, row 0 of table is changed in the method while it
> creates row 1, but I don't understand why and don't know how to keep
> it from changing. From this behavior, it's leading me to believe
> ArrayLists are passed by value or is this the way of ArrayLists? I
> thought parameters were passed by reference? What am I missing here?
Row 0 is changing because the parameters are being passed by reference.
You send in the list of items, and it simultaneously affects both the
to-be-returned value and the input (rows 1 and 0, respectively). To keep
it from changing, you want to create a copy of the row, which is what
the first line of my method does.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
|
| |
|
| |
 |
Lew

|
Posted: 2007-11-12 0:18:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Joshua Cranmer wrote:
> Row 0 is changing because the parameters are being passed by reference.
According to Sun and the language lawyers, the parameters are passed by value.
The values happen to be references.
> You send in the list of items, and it simultaneously affects both the
> to-be-returned value and the input (rows 1 and 0, respectively). To keep
> it from changing, you want to create a copy of the row, which is what
> the first line of my method does.
As did the code I posted to the first version of this question.
> public class Matriculate
> {
> List< List <Integer> > table
> = new ArrayList< ArrayList <Integer> > ();
>
> public Matriculate()
> {
> // the table will now contain zero rows
> assert table.size() == 0;
>
> // here row is declared the one and only time
> // and initialized for the first of more than one time
> List <Integer> row = new ArrayList <Integer> ();
> row.add( 1 );
> row.add( 2 );
> row.add( 3 );
> row.add( 5 );
>
> table.add( row );
>
> // the table will now contain one row
> assert table.size() == 1;
>
> row = new ArrayList <Integer> ();
> // notice - re-used, not re-declared
> // the variable 'row' now points to a whole
> // new ArrayList
> row.add( 1 );
> row.add( 2 );
> row.add( 4 );
> row.add( 8 );
> row.add( 16 );
>
> table.add( row );
>
> // the table will now contain two rows
> assert table.size() == 2;
> }
> // now the variable 'row' is out of scope
> // the closing curly brace killed it
>
> public List< List <Integer>> getTable()
> {
> return Collections.unmodifiableList( table );
> }
> }
--
Lew
|
| |
|
| |
 |
Taria

|
Posted: 2007-11-12 1:22:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Looking back, I see it now. To be honest, Lew, your code intimidated
me because of all the new statements it (new to me anyway.) There are
quite a few new keywords I liked that I want to try using once I get
the basic structure down for my program. Your code is one of those
things that I have to read multiple times on different days to
understand like Cormen's book.
Thanks to Daniel, Donald and Lew, I now understand how to manipulate
an ArrayList within a block and method. I think I can finish this
homework project that I have to do with the concepts I have learned in
the last few days. I'm about 15% done.
Personally, I think it's odd that you have to make a copy of a passed
parameter before using it to avoid modifying it within a method. I
thought that the parameters retained their value (if passed by
reference) despite modification during the course of the method
activation. I'm going to have to try experimenting with this part
after I'm done with this program! :)
-t (the grateful Newbie Java programmer)
|
| |
|
| |
 |
Daniel Pitts

|
Posted: 2007-11-12 6:01:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Taria wrote:
> Personally, I think it's odd that you have to make a copy of a passed
> parameter before using it to avoid modifying it within a method. I
> thought that the parameters retained their value (if passed by
> reference) despite modification during the course of the method
> activation. I'm going to have to try experimenting with this part
> after I'm done with this program! :)
>
> -t (the grateful Newbie Java programmer)
>
>
Actually, the way it works, is when you use "new Something", it
allocates the room for the Something object, and does all its
initialization "magic".
After that, you have exactly one Something, and anything that references
it references the exact same Something object. The references
themselves are copied, but the object they reference isn't copied or moved.
In other words, the semantics of Java parameters are that primitives and
references are passed-by-value, but objects are only accessible through
a reference, so the objects are never passed-by-value.
Hope this clarifies things.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
|
| |
|
| |
 |
Roedy Green

|
Posted: 2007-11-12 7:11:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
On Sun, 11 Nov 2007 09:22:14 -0800, Taria <email***@***.com> wrote,
quoted or indirectly quoted someone who said :
>Personally, I think it's odd that you have to make a copy of a passed
>parameter before using it to avoid modifying it within a method. I
>thought that the parameters retained their value (if passed by
>reference) despite modification during the course of the method
>activation.
You don't quite get it yet. Let me try yet another explanation.
When you call a method, a COPY of the value of the argument is passed
to the stack to become the local parameter inside the method. If you
modify it in the method, it won't charge any variables in the caller,
but it will change the value of your local variable.
If you use the word "final" on your parameter, if you try to modify
the value, the compiler won't let you.
If you need both the original value of the argument and a modified
value, you will need two variables, one to hold the old and one to
hold the new value. However, even in that case the caller's variables
will be untouched.
See http://mindprod.com/jgloss/parameter.html
http://mindprod.com/jgloss/argument.html
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
|
| |
|
| |
 |
Roedy Green

|
Posted: 2007-11-12 7:13:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
On Sun, 11 Nov 2007 14:00:41 -0800, Daniel Pitts
<email***@***.com> wrote, quoted or indirectly
quoted someone who said :
>In other words, the semantics of Java parameters are that primitives and
>references are passed-by-value, but objects are only accessible through
>a reference, so the objects are never passed-by-value.
see http://mindprod.com/jgloss/callbyreference.html
http://mindprod.com/jgloss/callbyvalue.html
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
|
| |
|
| |
 |
curt

|
Posted: 2007-11-12 8:10:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Roedy Green <email***@***.com> wrote:
> On Sun, 11 Nov 2007 09:22:14 -0800, Taria <email***@***.com> wrote,
> quoted or indirectly quoted someone who said :
>
> >Personally, I think it's odd that you have to make a copy of a passed
> >parameter before using it to avoid modifying it within a method. I
> >thought that the parameters retained their value (if passed by
> >reference) despite modification during the course of the method
> >activation.
[snip]
> If you need both the original value of the argument and a modified
> value, you will need two variables, one to hold the old and one to
> hold the new value. However, even in that case the caller's variables
> will be untouched.
I generally try to not modify pass by value parameters as a matter of
style. I don't always follow my own rules but most the time, if I need to
modify it, I will normally create a new local variable and only modify the
local variable. I find that it's very common that you will need the
original value at some point in the future and it's also common to not
always notice that the argument was modified locally. It's a nasty way for
obscure bugs to creep into the code when the argument is only modified on
certain rare conditions so the code added later that assumes it is working
with the original value only breaks on the rare conditions.
I find it's best to logically think of arguments as final (aka read only).
Logically, it's better to treat the parameter as belonging to the calling
code and not belonging to the local code even though pass by value
arguments are technically local. I think it helps you keep the correct
mindset when you deal with the parameters that aren't passed by value (the
contents of all objects and arrays).
> See http://mindprod.com/jgloss/parameter.html
> http://mindprod.com/jgloss/argument.html
--
Curt Welch http://CurtWelch.Com/
email***@***.com http://NewsReader.Com/
|
| |
|
| |
 |
Roedy Green

|
Posted: 2007-11-12 8:24:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
On 12 Nov 2007 00:10:25 GMT, email***@***.com (Curt Welch) wrote, quoted
or indirectly quoted someone who said :
>
>I find it's best to logically think of arguments as final (aka read only).
>Logically, it's better to treat the parameter as belonging to the calling
>code and not belonging to the local code even though pass by value
>arguments are technically local.
I have got into the habit of marking everything final, then removing
the final if I have to. It is amazing when you do that how few
non-final variables there are. I almost wish variables were final by
default and you had to declare them "mutable".
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
|
| |
|
| |
 |
Daniel Pitts

|
Posted: 2007-11-12 8:30:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Roedy Green wrote:
> On 12 Nov 2007 00:10:25 GMT, email***@***.com (Curt Welch) wrote, quoted
> or indirectly quoted someone who said :
>
>> I find it's best to logically think of arguments as final (aka read only).
>> Logically, it's better to treat the parameter as belonging to the calling
>> code and not belonging to the local code even though pass by value
>> arguments are technically local.
>
> I have got into the habit of marking everything final, then removing
> the final if I have to. It is amazing when you do that how few
> non-final variables there are. I almost wish variables were final by
> default and you had to declare them "mutable".
True that.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
|
| |
|
| |
 |
Chris ( Val )

|
Posted: 2007-11-12 13:31:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
On Nov 12, 11:24 am, Roedy Green <email***@***.com>
wrote:
> On 12 Nov 2007 00:10:25 GMT, email***@***.com (Curt Welch) wrote, quoted
> or indirectly quoted someone who said :
>
>
>
> >I find it's best to logically think of arguments as final (aka read only).
> >Logically, it's better to treat the parameter as belonging to the calling
> >code and not belonging to the local code even though pass by value
> >arguments are technically local.
>
> I have got into the habit of marking everything final, then removing
> the final if I have to.
[snip]
That sounds like a good idea. I got into the
same habit when passing objects around in C++.
But this leads me to a question.
In C++, if I marked a parameter of a function as
'const', then I could not operate on that parameter
at all, no matter if I used pass by value or pass
by reference semantics, for objects or primitive
types.
However, in Java, when using the 'final' keyword in
method parameters for reference object types, it does
not provide the same protection, as the object can still
be modified, and only the reference itself can't be changed.
So my question question is:
How do you stop the modification of an object, via
the client working directly on the method parameter?
|
| |
|
| |
 |
Lew

|
Posted: 2007-11-12 13:43:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Chris ( Val ) wrote:
> How do you stop the modification of an object, via
> the client working directly on the method parameter?
Make the parameter be of an immutable type.
If you must use a mutable type, have the subroutine make a defensive copy of
the argument and work on that instead.
--
Lew
|
| |
|
| |
 |
Chris ( Val )

|
Posted: 2007-11-12 14:16:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
On Nov 12, 4:42 pm, Lew <email***@***.com> wrote:
> Chris ( Val ) wrote:
>
> > How do you stop the modification of an object, via
> > the client working directly on the method parameter?
>
> Make the parameter be of an immutable type.
If I have control over the class design, I guess that is one way.
Or, did you perhaps mean to wrap up the object?
> If you must use a mutable type, have the subroutine make a defensive copy of
> the argument and work on that instead.
I was afraid of that, as it ultimately puts a
lot more responsibility on the developer.
Thank you.
|
| |
|
| |
 |
curt

|
Posted: 2007-11-12 14:16:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Lew <email***@***.com> wrote:
> Chris ( Val ) wrote:
> > How do you stop the modification of an object, via
> > the client working directly on the method parameter?
>
> Make the parameter be of an immutable type.
>
> If you must use a mutable type, have the subroutine make a defensive copy
> of the argument and work on that instead.
The object which is being passed must protect itself if it doesn't want to
be changed. To start with, the instance vars can be changed to private or
protected to keep outside code from referencing or changing the instance
variables directly, and then the protection is a function of what methods
are available. Making instance variables private by default is good
practice in general.
If the issue is that the calling object doesn't want the object passed to
be modified, there is no simple way to do it. If possible, make a copy of
it before you pass it as Lew said. Or you could wrap it in a wrapper class
which is a subclass of the object it is wrapping, and override all the
methods which mutate the object and disable them. But that's a excessive
measure if you only goal is to reduce the odds of bugs in the code.
There are no simple keywords like const to disable all modifications to a
passed argument.
--
Curt Welch http://CurtWelch.Com/
email***@***.com http://NewsReader.Com/
|
| |
|
| |
 |
Daniel Pitts

|
Posted: 2007-11-13 1:08:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Lew wrote:
> Chris ( Val ) wrote:
>> How do you stop the modification of an object, via
>> the client working directly on the method parameter?
>
> Make the parameter be of an immutable type.
>
> If you must use a mutable type, have the subroutine make a defensive
> copy of the argument and work on that instead.
>
Actually, in reality this defeats several OO principals. If you think
of the method call as a message, then that message handler should be
free to issue other messages to any objects that it knows about. If you
have a good design, then the handler (method) won't do something its not
supposed to.
Indeed, if you have an ill-behaved object that modifies its own state
when it shouldn't, then you need to make a defensive copy.
Well, that's true in theory at least. I haven't played around with that
concept, so take that advice with a grain of salt and think for yourself
what fits bets :-)
Daniel.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
|
| |
|
| |
 |
Lew

|
Posted: 2007-11-13 2:12:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Daniel Pitts wrote:
> Lew wrote:
>> Chris ( Val ) wrote:
>>> How do you stop the modification of an object, via
>>> the client working directly on the method parameter?
>>
>> Make the parameter be of an immutable type.
>>
>> If you must use a mutable type, have the subroutine make a defensive
>> copy of the argument and work on that instead.
>>
> Actually, in reality this defeats several OO principals [sic]. If you think
> of the method call as a message, then that message handler should be
> free to issue other messages to any objects that it knows about. If you
> have a good design, then the handler (method) won't do something its [sic] not
> supposed to.
A good design might include making a defensive copy so that the handler method
won't do something it's not supposed to do.
There is no violation of "OO" principles there.
--
Lew
|
| |
|
| |
 |
Taria

|
Posted: 2007-11-13 18:29:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
On Nov 11, 2:10 pm, email***@***.com (Curt Welch) wrote:
> Roedy Green <email***@***.com> wrote:
> > On Sun, 11 Nov 2007 09:22:14 -0800, Taria <email***@***.com> wrote,
> > quoted or indirectly quoted someone who said :
>
> > >Personally, I think it's odd that you have to make a copy of a passed
> > >parameter before using it to avoid modifying it within a method. I
> > >thought that the parameters retained their value (if passed by
> > >reference) despite modification during the course of the method
> > >activation.
>
> [snip]
>
> > If you need both the original value of the argument and a modified
> > value, you will need two variables, one to hold the old and one to
> > hold the new value. However, even in that case the caller's variables
> > will be untouched.
>
> I generally try to not modify pass by value parameters as a matter of
> style. I don't always follow my own rules but most the time, if I need to
> modify it, I will normally create a new local variable and only modify the
> local variable.
I definitely like that idea of making a local variable and only
modifying that instead of the passed variable. I think I will adopt
this style.
|
| |
|
| |
 |
Lew

|
Posted: 2007-11-13 21:43:00 |
Top |
java-programmer >> Newbie Question - ArrayLists and methods
Taria wrote:
> I definitely like that idea of making a local variable and only
> modifying that instead of the passed variable. I think I will adopt
> this style.
public class Eg
{
public static void modify( Foo foo )
{
Foo local = foo;
local.setName( "bar" );
}
}
If another method calls modify(Foo) then the name attribute of the passed
object will change.
public void cranitz()
{
Foo arg = new Foo();
arg.setName( "arg" );
Eg.modify( arg );
System.out.println( arg.getName() ); // displays "bar"
}
If the called method copies the passed object, then the method is unable to
alter the original object. If it merely points a local variable to the
(mutable) passed object, naturally the method can alter the object through its
local pointer.
--
Lew
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- JTree with dynamically adjusted row height during editing.I have extended JTable so that the installed editor for a cell checks
at each keystroke whether it must adjust the row height in order to fit
the content in the cell. This is easy to do with a document listener
which just starts a thread on each insertion to check for a height
change, and then calls setRowHeight on the appropriate row.
However, it does not seem to be so simple to do the same thing with a
JTree. setRowHeight cannot be called on a specific row, and with
rowHeight set to 0, the tree cells are only resized when the tree
manager itself queries the height. There does not appear to be a way
to get the editor to do this directly.
Does anyone know how to get this effect? It allows for something much
like a regular text outliner using JTree and I would think lots of
people would have wanted to do this in the past, but I havent found
evidence that it has been done.
- 2
- 3
- Synth L&F as jarHello,
i am trying to build a L&F basedf on Synth but now i have problems
using the L&F in another project. I pack the L&F into jar add it to a
projects classpath but it is not possible to access the images
contained in the jar. I know that resources from a jar should be
accessed by:
MyResourceBase.class.getResource("path/relative/to/the/MyResourceBase.png")
the problem is that its not me who accesses the images but synth. AND
when i look into synths code the images should be loaded by:
new ImageIcon(url, null).getImage()
with url is the return of:
private URL getResource(String path) {
return _resourceBase.getResource(path);
}
That looks correct to me but it does not work. Has anyone build his
synth L&F and got it to work from a jar? If that does not work, what is
a custom L&F good for if it can not be deployed as a jar?
I am very thankfull for all hints
Harri E.
- 4
- Piped stream help.Hi Everyone,
I have two servlets that both need access to a data file. I would like to
have a 'driver' program that takes care of writing / reading objects to the
data file and i would like the driver program to be able to communicate
objects to each servlet. Can i do this w/ pipedinput / output streams? I do
not understand how i can reference a piped output stream in one object from
another!
TIA, Andrew.
- 5
- A specific external package import from javacWhich file(s) are required?
Where should these file(s) go?
What's the javac syntax to compile Test16 into ...\class\?
Given this directory structure:
C:\java\java\jTidy\Test16.java
C:\java\org\w3c\
C:\java\class\
Given that Test16.java has this import:
import org.w3c.tidy.Tidy;
SSCE @ <http://thufir.lecktronix.net/java/Test16.java>
Here's what I've gleaned from the 'net:
C:\java> javac -d . org\w3c\* C:\java\java\*
Clearly not correct, but that's my best effort at this point :(
thank you,
Thufir Hawat
- 6
- JNI: call C-main program from JavaI have a C-program which calls Java functions through JNI.
The C-part runs okay, and I want to debug the Java code.
For that reason, I want to start the Java debugger and then start the
C-main program through JNI. After that I hope I can set
breakpoints within the Java part and start debugging.
In the documents I saw that "System.LoadLibrary()" can load
only DLL's and shared object, but no main-program.
Thanks for any help,
Josef
- 7
- Help! I don't know where to turn.> Then I went to java.sun.com and decided I have old packages and was
> going to upgrade everything. As far as I can tell, I downloaded the
> following:
>
> - the JS2E 1.5.0 (?)
> - the JDK
> - the JVM
> - the NetBeans 4.1 (?) bundle
> - the documentation tree
>
> So this seems hunky-dory. The problem now is two-fold:
>
> (a) I can't start the Java console anymore (I saw it once and it looks
> totally different than the previous version) though everytime I
> doubleclick the coffee mug icon in the Control Panel, it starts a new
> instance of javaw.exe.
> (b) Now my Mozilla Thunderbird 1.6 won't connect to my email server to
> retrieve my email.
>
> Can anyone provide some assistance or point me to the right place?
> Many thanks!
>
> Mike
If you have downloaded the J2SE 1.5.0 SDK (or the JDK 1.5.0) and ran
the installation, you do not need to install JVM (i assume you mean
JRE). The java console will look different if you have installed the
JDK.
I am not sure if you can keep two jdks installed. It is possible, but
if you want to save yourself frustation, uninstall the previous jdk
(and jre. Installing the jdk installs jre too along with it. :) ) and
install the new one.
Dont know about netbeans. Possibly, it needs the JAVA_HOME variable
set.
Also the documentation is totally separate. You just need to unzip to a
folder to read it, and not install. Its just a bunch of html files. Do
not worry about it. You can have as many docs of different versions as
you want.
Probably you messed up the internet settings so the problem with
thunderbird. nothing to do with java i suppose. not sure since i have
not used thunderbird yet.
- 8
- Playing (MIDI) sounds from Java applet (Shepard's Tones)
The applet for endlessly rising/falling scale
(auditory illusion)
on this page is fantastic!
http://www.cs.ubc.ca/nest/imager/contributions/flinn/Illusions/ST/st.html
How is this done?
(I'm assuming it uses MIDI.)
Is this sound applet playable from any
java-enabled browser on any Windows system?
How about on Mac or Unix?
I'm asking because I want to write
Java programs that plays simple
2-part inventions by Bach.
Thanks.
http://geocities.com/SOBlikeMIDIs/
__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com
- 9
- [OT] SourceForge AddReleaseTaskOfftopic: A question about HTTPS / Java:
I'm writing an Ant task to automate the SourceForge 'Add release' procedure.
For this I'm using Jakarta Commons Net and HttpClient.
The task can be used in an Ant build file as follows:
<taskdef name="sfaddrelease"
classname="org.xins.util.ant.sourceforge.AddReleaseTask"
classpath="xins-common.jar:commons-net.jar:commons-httpclient.jar"
/>
<sfaddrelease
user="znerd"
password="${password}"
file="build/xins-${version}.tar.gz"
group="71598"
package="71219"
release="${version}"
/>
The login is done using HTTPS. The Commons HttpClient library supports this.
But apparently, the server is not trusted, because I get a
javax.net.ssl.SSLHandshakeException. The message is:
"java.security.cert.CertificateException: Could not find trusted
certificate"
Apparently, I need to get the certificate of sourceforge.net and store it in
a keystore. Perhaps I should use 'keytool -import' for this, in some way.
Questions:
* How do I get the certificate of sourceforge.net?
* How do I store it in a file so that Java will accept it?
Ernst
_______________________________________________
email***@***.com mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-java
To unsubscribe, send any mail to "email***@***.com"
- 10
- EnterpriseBean and finalize()Hi Everyone,
I'm trying to learn EJB and picked up a copy of the book "SCBCD Exam
Study Kit" by Paul Sanghera. Inside it, I came across the following
sentence, which piqued my interest because I cannot see a) where this
can be found in the EJB 2.0 specification (actually, I was looking in
the J2EE 1.3 specification), or b) why finalizing a bean would be
interfering with the responsibilities of the container. Here's the
quote:
"... the bean class must not have any finalize() method because by
doing this you would be stepping on the container's toes, since it is
the responsibility of the container to manage the lifecycle, threads,
garbage collection, and so forth."
If anyone can shed a little light on this, and dispel the confusion,
I'd really appreciate it.
Many thanks,
Jono
- 11
- Use of JVM id and Event Notifier patternIn our design for event subscription/publication, a JVM id is used to
identify the event channels (or event brokers). The JVM id refers to
an EventChannel on a host and there will be one EventChannel per host.
FYI, More information about Event Notifier pattern is available at:
http://members.ispwest.com/jeffhartkopf/notifier/
Is it okay to refer to JVM id (kernel level details) to identify a
user level class like EventChannel ? I feel that EventChannel should
be referred by some other way.
Any pointers will be appreciated.
B.
- 12
- using importI'm trying to import the Welomb class in the java divelog tutorial into
another application. But when I type import divelog.* it refuses
the absolute path for Welcome is
d:\Documents\Java\Divelog\src\divelog
the application I'm trying to import it from is at
d:\Documents\Java\Frames\src\frames
I've also tried creating a library (MyLibrary) and pointing to the
divelog.jar file and setting the classpath to point at divelog.jar. I've
then added the library to my project but when I try and create a Welcome
class it says it cant find the class. So neither using a library or
importing work.
I'm using sun java studio enterprise8 (free) does anyone know how to import
the divelog package into my app using an import statement.
I've tried the following with no success
import divelog.*
import Documents.Java.Divelog.src.divelog.*
in both cases I get package diesnt exist
any suggestion welcome!!
- 13
- Newbie:Please suggest ebook or any reading material for creating rich clients interfaces in javaWhile googling I found a very interesting presentation on creating
amazing GUI's in java on this link -
http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-3548&yr=2007&track=2
. I was very much impressed and really want to read and learn more on
developing such interfaces. So please suggest some reading material
for this.
I know core java and basics of swing.
Still learning java..:)
- 14
- AES-RijndaelI am doing an entry in the Java glossary on AES aka
Rijndael symmetric cipher.
I wonder if anyone knows of opensource Java implementations.
see http://mindprod.com/jgloss/aes.html
for what I have discovered so far.
--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
- 15
- sourse & installationhere i'm for asking to u all that how can i install or download java
run time base running with console via internet.
|
|
|