Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
tef
May 30, 2004

-> some l-system crap ->

Fruit Smoothies posted:

While we're on the subject of sockets; I've always prefered async non-blocking. Can someone tell me why I should do sync blocking instead? Should I?

I was under the impression that nio was the way to go for performance.

Adbot
ADBOT LOVES YOU

Contra Duck
Nov 4, 2004

#1 DAD

tef posted:

I was under the impression that nio was the way to go for performance.

Yeah, threads are expensive and having a separate one to handle each connection can quickly get out of hand. Though on the client side where you're usually only maintaining one connection blocking IO is plenty good.

Fruit Smoothies
Mar 28, 2004

The bat with a ZING
I feel a lot happier now. gently caress threads most of the time, anyway.

Tulenian
Sep 15, 2007

Getting my 'burg on.

Contra Duck posted:

Yeah, threads are expensive and having a separate one to handle each connection can quickly get out of hand. Though on the client side where you're usually only maintaining one connection blocking IO is plenty good.

Just make sure your blocking socket isn't running on the main thread. Nothing worse for user experience than having a program's user interface freeze up simply because it's waiting for data from the server.

Fehler
Dec 14, 2004

.

Contra Duck posted:

It'll look a little different to that example, it'll probably require two threads, but the general principle is the same. You'll have a Selector object and a thread that is listening for connections and adding SocketChannels to the Selector. Then you'll have a second thread that asks the Selector for any Channels that are ready to be read. The SelectionKey determines the operation you're looking for, in that example it's set to ACCEPT but if you use READ then it'll return all the channels ready to be read.
Thanks, but what I don't really get about non-blocking sockets is how I do the reading and writing. From what I read in the docs the only way is to read/write strings encoded as ByteBuffers using the methods from the SocketChannel. But the docs also say that it's not always guaranteed that the entire string will actually be sent/received in one call, and I'm not really sure how to work with that.

Also, I was using serialization with ObjectStreams in order to transfer a special class between client and server which then encoded a message ID and the data. Would I really have to manually encode these objects as byte arrays and then decode them again on the other end in order to make them work here? Is that even feasible?

I think I might just try using threads for now, since I would really like to avoid writing thousands of lines of low-level code just to avoid using threads.

In that case I'd have another question though - in order to do this with threads I would have to open a socket in the client, constantly check whether there is any new data to read or write and then call the appropriate functions on the stream. I kinda have an idea how to do the writing part, but how do I determine whether there is any new data? I thought InputStream.available() would do that, but apparently not.

SHODAN
Feb 20, 2001

NARCISSISTIC QUEEN BITCH:
ASK ME ABOUT BEING BETTER THAN YOU
This is probably a dumb question, but I've been doing some development on Java apps for Blackberry devices using their Java IDE, and I need to tie in some MySQL fetching. Is it actually possible to import the MySQL J connector?

I've tried doing this in the IDE and placing the .jar file and/or the com/org subfolders in the classpath, and even in the project directory itself with no success. It seems like the IDE can't import anything outside of the standard rim libraries (com.rim, net.rim, etc).

Is this even possible? If not (since the data being pulled is fairly simple) I could just use some sort of php solution, but it'd really be nice to just be able to pull the data directly.

Contra Duck
Nov 4, 2004

#1 DAD

Fehler posted:

Thanks, but what I don't really get about non-blocking sockets is how I do the reading and writing. From what I read in the docs the only way is to read/write strings encoded as ByteBuffers using the methods from the SocketChannel. But the docs also say that it's not always guaranteed that the entire string will actually be sent/received in one call, and I'm not really sure how to work with that.

Also, I was using serialization with ObjectStreams in order to transfer a special class between client and server which then encoded a message ID and the data. Would I really have to manually encode these objects as byte arrays and then decode them again on the other end in order to make them work here? Is that even feasible?

I think I might just try using threads for now, since I would really like to avoid writing thousands of lines of low-level code just to avoid using threads.

Fair enough. The stuff in java.nio is very powerful but it is quite difficult to get your head around initially and probably not worth it for a small project.

quote:

In that case I'd have another question though - in order to do this with threads I would have to open a socket in the client, constantly check whether there is any new data to read or write and then call the appropriate functions on the stream. I kinda have an idea how to do the writing part, but how do I determine whether there is any new data? I thought InputStream.available() would do that, but apparently not.

If you're using blocking methods you don't have to concern yourself with figuring out if there's data waiting to be read, just ask for some data and it'll block until it finds it. If you're passing around serialised objects you'll want to use an ObjectInputStream like this:

code:
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
while (true)
{
    GameMessage message = (GameMessage) objectInputStream.getObject();
    processGameMessage(message);
}
You'll need to run this in a separate thread though, or like Tulenian said the blocking operation will stop the rest of your program as well.

Contra Duck fucked around with this message at 11:41 on Jun 29, 2009

Volguus
Mar 3, 2009

Contra Duck posted:



You'll need to run this in a separate thread though, or like Tulenian said the blocking operation will stop the rest of your program as well.

Be careful how do you do this. Usually the UI frameworks are not thread safe. That is: you should not update a UI component from a thread other than the tread who created it. This is true for most (if not all) of them.

Here is a tutorial for concurrency in Swing:
http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html

ashgromnies
Jun 19, 2004
I am a complete Java neophyte who was thrown into maintaining a big ol' app.

Anyhow, I have a method that should grab one row from the database and return one specific column from it.

This is all with JDBC.

The current implementation is using ResultSet.getInt to get the value of that column - but how do the offsets for getInt work? Do they start at 0 or 1? The JavaDoc doesn't say:

code:
[b]JavaDoc[/b]

 int 	getInt(int columnIndex)
          Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.
Here's the code I'm looking at...

It SHOULD be returning 0, but for some reason it's returning 1.

code:
    protected int fetchQuantity(DB db) throws SQLException {
        // Insert a dummy row, if necessary, to ensure the subsequent SELECT succeeds to lock the row.
        String sql = "INSERT IGNORE INTO my_table (id_column, quantity_column) VALUES (?, 0)";
        PreparedStatement statement = db.prepare(sql);

        try {
            statement.setInt(1, this.uniqueId);
            statement.execute();
        } finally {
            statement.close();
        }

        sql = "SELECT quantity_column FROM my_table WHERE id_column = ? FOR UPDATE";
        statement = db.prepare(sql);

        try {
            statement.setInt(1, this.uniqueId);

            ResultSet results = statement.executeQuery();
            if (results.next()) {
                return results.getInt(1);
            }
        } finally {
            statement.close();
        }

        // If we get here something went badly wrong.  Log the error
        log.error("failed: unable to establish prior quantity");
        return getQuantity();
}
Now, I'm not seeing the "failed" log message so I know it's not getting there.

Is the getInt index being used correctly?

baquerd
Jul 2, 2007

by FactsAreUseless

ashgromnies posted:

Is the getInt index being used correctly?

Yes.

code:
int getInt(int columnIndex)
           throws SQLException

    Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.

    Parameters:
        columnIndex - the first column is 1, the second is 2, ... 
    Returns:
        the column value; if the value is SQL NULL, the value returned is 0 
    Throws:
        SQLException - if a database access error occurs
Are you 100% sure your insert statement isn't throwing an error, for example a duplicate primary key entry? The IGNORE keyword is terrible.

ashgromnies
Jun 19, 2004

quadreb posted:

Yes.

code:
int getInt(int columnIndex)
           throws SQLException

    Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.

    Parameters:
        columnIndex - the first column is 1, the second is 2, ... 
    Returns:
        the column value; if the value is SQL NULL, the value returned is 0 
    Throws:
        SQLException - if a database access error occurs
Are you 100% sure your insert statement isn't throwing an error, for example a duplicate primary key entry? The IGNORE keyword is terrible.

Since it's in a try/finally block wouldn't nothing happen if it did throw an error? That's intended - there should be one row in that table per value of id_column, defaulting at 0. That insert is just so the select on the next line will retrieve a row.

I mean, it should throw a duplicate primary key error most of the time, but it's in a try block. That's intended by the original programmer.

Mill Town
Apr 17, 2006

Have you actually looked at the database and checked what's in there?

ashgromnies
Jun 19, 2004

Mill Town posted:

Have you actually looked at the database and checked what's in there?

Yes. One row with unique_id = 1, quantity_column = 0

It calls the method on an instance where this.uniqueId == 1

Mill Town
Apr 17, 2006

Hey, do you know which return statement it's returning from? I notice that if an exception is thrown inside either try block, after you fall out of the finally block, you do this:

return getQuantity();

Does that, perhaps, return 1?


Durf, just noticed you said you're not seeing the failed log message.

ashgromnies
Jun 19, 2004

Mill Town posted:

Hey, do you know which return statement it's returning from? I notice that if an exception is thrown inside either try block, after you fall out of the finally block, you do this:

return getQuantity();

Does that, perhaps, return 1?


Durf, just noticed you said you're not seeing the failed log message.

Yeah, it's not getting to the failed line... it's a really weird issue. I'm trying to get a local copy of the application running right now instead of debugging it on the server it's running on.

Working with Eclipse is such a pain in the rear end coming from a Perl/Python and vim background.

Volguus
Mar 3, 2009

ashgromnies posted:

Yeah, it's not getting to the failed line... it's a really weird issue. I'm trying to get a local copy of the application running right now instead of debugging it on the server it's running on.

Working with Eclipse is such a pain in the rear end coming from a Perl/Python and vim background.
The reason is doesn't get to the failed line is because is throwing an exception.
most likely a SQLException.

You just need a good old try/catch/finally. In the catch block, the least you can do is :
code:
catch(SQLException ex){
ex.printStackTrace();
}
It does wonders for debugging. It may even tell you in plain english the answer to the most important question of them all: WHY?

baquerd
Jul 2, 2007

by FactsAreUseless

rhag posted:

The reason is doesn't get to the failed line is because is throwing an exception.
most likely a SQLException.

I think we all forgot code after an uncaught exception is thrown doesn't run, even if the exception is thrown in a try block. Good call.

Randomosity
Sep 21, 2003
My stalker WAS watching me...
Hibernate question for everyone.

I've got a custom user type in several class. It works fine, the way it's supposed. However, any time I change a model, it does not mark the model as changed (and therefore, does not update the DB), unless another non-custom-type field is changed.

Any ideas on this?

ashgromnies
Jun 19, 2004

quadreb posted:

I think we all forgot code after an uncaught exception is thrown doesn't run, even if the exception is thrown in a try block. Good call.

Yep. Wound up being a really annoying transaction issue - that method winds up being called twice as part of making one call to the application, but it winds up getting a different database transaction each time... so the first time it's called, it is on one transaction, performs the INSERT IGNORE, transaction not committed, then a little later it's still not committed and it calls that method again but with a different transaction this time, and it winds up locking and everything falls to poo poo and it falls through and winds up returning the results of that getQuantity call which will be 1.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Randomosity posted:

Hibernate question for everyone.

I've got a custom user type in several class. It works fine, the way it's supposed. However, any time I change a model, it does not mark the model as changed (and therefore, does not update the DB), unless another non-custom-type field is changed.

Any ideas on this?

I had this issue during development over a year ago. I just had to either manually modify the database or drop the table and let Hibernate recreate it, I never found a way around it.

Randomosity
Sep 21, 2003
My stalker WAS watching me...
Alright, I think I can clarify the issue.

Basically, I've got this class:
code:
@Entity
class TableName {
      Integer primitiveField
      @Type(type="custom.library.usertype")
      List listOfThings

      //Getter and setters
}
Now, let's say I do this (using Groovy/Grails, so hibernate calls are behind the scenes, but it's there, trust me):
code:
     TableName instance
     instance.listOfThings = new ArrayList()
     instance.listOfThings.add(1)
     instance.save()
If I go to the DB, the 'listOfThings' field is unchanged. It is only when
code:
     instance.primitiveField = 1
is added that the DB changes.

Now, Hibernate only writes to the DB when it detects that there was a change in the model. It seems like hibernate doesn't detect the custom type as being changed (or, maybe, the List being changed?)? Is there a way I can tell a hibernate model, "No, seriously, you were changed, write this field."

EDIT: It seems like, because the reference hasn't changed, Hibernate assumes it's the same thing. I wonder if I should be using Hibernate's list instead of Java.util's.

Randomosity fucked around with this message at 18:10 on Jul 1, 2009

ashgromnies
Jun 19, 2004
So there's this other monolithic Java web application we're running.

It has a memory leak somewhere, no one has been able to diagnose it exactly but we need to run a nightly restart of the application right now.

Anyone have any tips for debugging memory leaks in Java applications or some sort of memory usage profiler that would let me track down what exactly isn't freeing its memory? I have no experience debugging memory leaks and I'm not really sure where to start exactly. The application is freaking enormous and a mess of spaghetti code and FactoryFactory's.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

ashgromnies posted:

Anyone have any tips for debugging memory leaks in Java applications or some sort of memory usage profiler that would let me track down what exactly isn't freeing its memory? I have no experience debugging memory leaks and I'm not really sure where to start exactly. The application is freaking enormous and a mess of spaghetti code and FactoryFactory's.

Generally you debug memory leaks by running the program in the profiler, doing a few operations, forcing a GC, and then taking a memory snapshot. Then you look at the largest / most commonly-allocated objects, and you see what's holding a reference to them. Any memory profiler worth the name should be able to do all that.

I found YourKit pretty reasonable; at least, it worked well enough for me, so I stopped looking.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Randomosity posted:

e:removed for brevity

You might have to use Hibernate's collection annotations (@OneToMany I think) for Hibernate to realize it needs to handle List internals. That said, I DID just gently caress up the deepCopy() method on an immutable class for a UserType I implemented just last week (in Grails) and it caused Grails to trigger a db save. However, that class was not a List (Grails domain classes and Lists are a disaster).

Any particular reason you are using a UserType and not another mapped Entity collection? Don't get me wrong, I use them myself, but the DB I work with is solid poo poo. I'd tend to stay away from them if at all possible.

trex eaterofcadrs fucked around with this message at 20:21 on Jul 1, 2009

WalletBeef
Jun 11, 2005

ashgromnies posted:

So there's this other monolithic Java web application we're running.

It has a memory leak somewhere, no one has been able to diagnose it exactly but we need to run a nightly restart of the application right now.

Anyone have any tips for debugging memory leaks in Java applications or some sort of memory usage profiler that would let me track down what exactly isn't freeing its memory? I have no experience debugging memory leaks and I'm not really sure where to start exactly. The application is freaking enormous and a mess of spaghetti code and FactoryFactory's.

JProfiler. It isn't free but you can download a trial version.

You can view memory usage over time, active objects, number of instances for each class type, amount of memory consumed by each object, etc. Go to their web page for a full list of features. With the help of JProfiler, I was able to cut the memory usage of an application by about 2/3rds.

Edmond Dantes
Sep 12, 2007

Reactor: Online
Sensors: Online
Weapons: Online

ALL SYSTEMS NOMINAL
Ok, let's see...
I was handed a little proggie which combs a database, looks for different values (Select distinct), and then replaces them with different correlative numbers. This was done in order to "mask" a database so we lowly offshore code monkeys could not access sensitive information.

They realized this approach sucked, and now they want to use different kinds of "mask data" depending on the original data type.

So numbers (like phone numbers, ip addresses and such) will still be replaced by 1, 2, 3 and so on, but Strings will have to be replaces by, well, letters.

I thought about using randomly generated strings of a fixed length, but they need to be different for every distinct result on the original table, and I think checking every newly generated one to see if it hasn't been already used would be a mess. I was then thinking about an alphanumeric "counter"; is there any way of taking a string (let's say "AAAAAAA" for example's sake), and transform it into "AAAAAAB", "AAAAAAC" and so on and so forth?

ashgromnies
Jun 19, 2004

WalletBeef posted:

JProfiler. It isn't free but you can download a trial version.

You can view memory usage over time, active objects, number of instances for each class type, amount of memory consumed by each object, etc. Go to their web page for a full list of features. With the help of JProfiler, I was able to cut the memory usage of an application by about 2/3rds.

How does it work exactly? Can I run it against a running instance of the application on our server and view the GUI on my local machine?

edit: ah ok it has remote profiling... nice. Thanks!

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Edmond Dantes posted:

Ok, let's see...
I was handed a little proggie which combs a database, looks for different values (Select distinct), and then replaces them with different correlative numbers. This was done in order to "mask" a database so we lowly offshore code monkeys could not access sensitive information.

They realized this approach sucked, and now they want to use different kinds of "mask data" depending on the original data type.

So numbers (like phone numbers, ip addresses and such) will still be replaced by 1, 2, 3 and so on, but Strings will have to be replaces by, well, letters.

I thought about using randomly generated strings of a fixed length, but they need to be different for every distinct result on the original table, and I think checking every newly generated one to see if it hasn't been already used would be a mess. I was then thinking about an alphanumeric "counter"; is there any way of taking a string (let's say "AAAAAAA" for example's sake), and transform it into "AAAAAAB", "AAAAAAC" and so on and so forth?

Yeah, you can use BigInteger(String val, int radix);

I use this for base-36 (0-9A-Z) conversions.

Sub Par
Jul 18, 2001


Dinosaur Gum
This doesn't deserve its own thread, and I looked through the thread as best I could, but I am planning on learning Java on my own. Can someone suggest a good book to serve as beginner's guide? I have little programming experience, other than a pretty good knowledge of VBA for applications, and I took a C++ class in high school (like 8 years ago). I do work with databases for a living, so I am intimately familiar with SQL and am a quick learner. Basically, I need to know things about Java specifically, not how to turn on the computer or what OOP is. Thanks.

edb
Sep 28, 2008

Make me a sandwich.

Sub Par posted:

This doesn't deserve its own thread, and I looked through the thread as best I could, but I am planning on learning Java on my own. Can someone suggest a good book to serve as beginner's guide? I have little programming experience, other than a pretty good knowledge of VBA for applications, and I took a C++ class in high school (like 8 years ago). I do work with databases for a living, so I am intimately familiar with SQL and am a quick learner. Basically, I need to know things about Java specifically, not how to turn on the computer or what OOP is. Thanks.

Sun's Java tutorials are always a good place to start - http://java.sun.com/docs/books/tutorial/

If you want a book, here is a list of what was recommended to me at university in my first year.

C. Horstmann, Java Concepts,
Deitel & Deitel, Java How to Program,
Y. Daniel, Introduction to Java Programming,
B. Eckel, Thinking in Java (Online version http://www.mindview.net/Books/TIJ/)

Flamadiddle
May 9, 2004

I've been learning Java on my own, too. First I was looking at the Sun tutorials mentioned above, but I picked up a second hand copy of the Deitel "How to Program" Java book for like £0.50, which is fine and seems to cover most stuff pretty well. Am only about 750 pages into it so far. It's a big-rear end book.

Sub Par
Jul 18, 2001


Dinosaur Gum
Thanks guys. I'll go with How to Program Java.

Bubblegum Wishes
May 22, 2007

I just wanted to point out another resource that's not in the OP.

I was recently talking to a group that works with java and uses Eclipse. I haven't had to look at java since school, but school was about 90% java so back then it was pretty strong, and I've never used Eclipse. So I set about looking for refresher material on both.

Eclipse has this series of videos. Its your entire java class from your second year of your CSE degree summarized and done in Eclipse.

Its baby stuff but I think he does an awesome job of explaining what hes doing and manages to teach you something about both java and general theory. Just FYI for anyone looking for a starting place with java.

Edit: I <3 Eclipse.

Bubblegum Wishes fucked around with this message at 01:39 on Jul 15, 2009

Save the whales
Aug 31, 2004

by T. Finn

Edmond Dantes posted:

I thought about using randomly generated strings of a fixed length, but they need to be different for every distinct result on the original table, and I think checking every newly generated one to see if it hasn't been already used would be a mess. I was then thinking about an alphanumeric "counter"; is there any way of taking a string (let's say "AAAAAAA" for example's sake), and transform it into "AAAAAAB", "AAAAAAC" and so on and so forth?

There is a way to generate unique ID strings.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html

code:
String uuid = java.util.UUID.randomUUID().toString();
If I remember correctly it contains letters, numbers, and hyphens. Would that suit your purpose?

zootm
Aug 8, 2006

We used to be better friends.

Bubblegum Wishes posted:

I just wanted to point out another resource that's not in the OP.

I was recently talking to a group that works with java and uses Eclipse. I haven't had to look at java since school, but school was about 90% java so back then it was pretty strong, and I've never used Eclipse. So I set about looking for refresher material on both.

Eclipse has this series of videos. Its your entire java class from your second year of your CSE degree summarized and done in Eclipse.

Its baby stuff but I think he does an awesome job of explaining what hes doing and manages to teach you something about both java and general theory. Just FYI for anyone looking for a starting place with java.

Edit: I <3 Eclipse.
Added it to the "Eclipse" section of the information post thing, cheers. :)

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Is there a simple way to create a list of references to objects? A rough sketch of what I'm trying to do...
code:
public class Goon {
   public Integer neckbeards;
   public String name = new String();
   public Boolean hasAClue;
   public Vector<Object> thingsICareAbout = new Vector<Object>(); 
  
   public static void main() {
   neckbeards = 1;
   name = "Gravity Pike";
   thingsICareAbout.add(neckbeards);
   neckbeards = 0;
   
   System.out.println(neckbeards.toString()+" vs "+thingsICareAbout.elementAt(0).toString());
   }
}
My output's going to be "1 vs 0", when I want it to be "0 vs 0" - I want the list to contain a reference to the variable, not the value of the variable. Is there a simple way to do this, without, say, creating a new class ThingsIMightCareAbout<U>, and having all of my variables be of this type? I'm a bit new to Java, and am perhaps thinking a bit too much as if I were coding in C++...

Volguus
Mar 3, 2009

Gravity Pike posted:

Is there a simple way to create a list of references to objects? A rough sketch of what I'm trying to do...
code:
public class Goon {
   public Integer neckbeards;
   public String name = new String();
   public Boolean hasAClue;
   public Vector<Object> thingsICareAbout = new Vector<Object>(); 
  
   public static void main() {
   neckbeards = 1;
   name = "Gravity Pike";
   thingsICareAbout.add(neckbeards);
   neckbeards = 0;
   
   System.out.println(neckbeards.toString()+" vs "+thingsICareAbout.elementAt(0).toString());
   }
}
My output's going to be "1 vs 0", when I want it to be "0 vs 0" - I want the list to contain a reference to the variable, not the value of the variable. Is there a simple way to do this, without, say, creating a new class ThingsIMightCareAbout<U>, and having all of my variables be of this type? I'm a bit new to Java, and am perhaps thinking a bit too much as if I were coding in C++...

Yes there is.
You see, in Java every object is a pointer. That is, you only work with references, you never work with values. The only time you would ever work with values is when working with primitives (char,boolean,int,double,etc.)

Since Java 1.5 one fantastically useful and nice feature has been added to Java: autoboxing. However, for new users this is confusing.
For more information about autoboxing read: http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html

Now, lets take your code and translate it (for you to see what you have done):

code:
public class Goon {
   public Integer neckbeards;
   public String name = new String();
   public Boolean hasAClue;
   public Vector<Object> thingsICareAbout = new Vector<Object>(); 
  
   public static void main() {
   neckbeards = new Integer(1);
   name = "Gravity Pike";
   thingsICareAbout.add(neckbeards);
   neckbeards = new Integer(0);
   
   System.out.println(neckbeards.toString()+" vs "+thingsICareAbout.elementAt(0).toString());
   }
}
So, you have basically created a new object everytime you do the Integer=int assignment. In Java 1.4 that would have not been permitted, now the compiler does the work for you.

The same is true with strings as well:
String a="a";
a="b";

The memory location of the first object is different from the memory location of the second one. These objects are ...special in Java. Strings have some operators overloaded, even though Java sdoesnt have operator overloading (concatenate strings with +, while == performs an .equals() ).
(One simple catch 22 situation: String extends Object, yet object has a public String toString() method.)

So in order to achieve your goal you should have your own object, with a setNeckbeards() method. Create one instance of that object, add it to the vector, set the neckbeards value to something else, and see it change everywhere that object is referenced.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Gravity Pike posted:

My output's going to be "1 vs 0", when I want it to be "0 vs 0" - I want the list to contain a reference to the variable, not the value of the variable.

There is no way of forming a reference to a local variable in Java. Doing so is either unsafe (as in C++) or expensive (as in JavaScript or Smalltalk). Unfortunately, this does make certain kinds of metaprogramming difficult or impossible.

If it's an instance variable, you can use closures (anonymous classes) to do sortof what you want, except with gratuitous amounts of syntax:

code:
interface Watcher<T> { T peek(); }
...

private Integer i;
void myMethod() {
  // implicitly closes on the value of this
  addInterest(new Watcher<Integer>() { public Integer peek() { return i; } });
  ...
  final List<Integer> vec = ...;
  ...
  // closes on the value of vec (which is why you have to declare it final)
  addInterest(new Watcher<Integer>() { public Integer peek() { return vec.size(); } });
  ...
}

Volguus
Mar 3, 2009

rjmccall posted:

There is no way of forming a reference to a local variable in Java.

What? What does the scope of a variable has to do with references ? What are you talking about?

MyNewObject obj=new MyNewObject();

obj is a reference. Global, local, static, final, whatever the hell you want. it is still a reference.

int i=1;
i will always point to the value of the variable, not to its location in memory. and in java you cannot even get that (like &i in C).

rjmccall posted:

Doing so is either unsafe (as in C++) or expensive (as in JavaScript or Smalltalk). Unfortunately, this does make certain kinds of metaprogramming difficult or impossible.

If it's an instance variable, you can use closures (anonymous classes) to do sortof what you want, except with gratuitous amounts of syntax:


I have no words for this...

Adbot
ADBOT LOVES YOU

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Let's get back to the real meat of this thread already: does java pass by value or by reference?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply