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
Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE
Hello Java question thread, I've been having some issues with some weird thing I want to do with JTables and was hoping you all might have some sort of input.

Basically I want to be able to register a "drag and drop" style action on a JTable. The default Drag and Drop implementation seems to be geared towards dragging between GUI elements and doesn't really give me any solid information on dragging from one cell to another inside the same table. Is there something obvious I'm missing in the drag and drop API or is it off to the mouse listener mines for me?

Sidenote : I've tried listening on mouseDragged events and it seems to fire three or four times and then just stop until I release and start dragging somewhere else (not firing a mouse button released event in the process :argh:)

Shavnir fucked around with this message at 22:55 on Apr 4, 2009

Adbot
ADBOT LOVES YOU

capr1ce
Oct 30, 2004

Hi, I was wondering if anyone has any experience with web applications and chinese characters? I read up a bit on the internet, but I feel totally out of my depth.

I'm using Struts. I have a web form, and I enter some chinese characters and submit it to a Struts action (which is basically a servlet for those that might not know). Trouble is, once it's been submitted to the action, the characters are converted to a string.

For example, 硼 becomes:
code:
硼
I'm guessing this is an HTML entity, because it displays properly when I put it into some HTML (as you can see I had to put it in a code tag!) - but not in a form field.

What I need to do is store it in a database, and then it needs to be searched against and displayed, and maybe edited in an html form. Is there anything I can do to convert this string back to the 硼 character in the Java code, or is it perfectly fine to put the HTML String into the database and search on that?

I have set my content type in my HTML page:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

Also I put this into my action:
request.setCharacterEncoding("UTF-8");

Thanks in advance in case anyone can help!

csammis
Aug 26, 2003

Mental Institution

capr1ce posted:

What I need to do is store it in a database, and then it needs to be searched against and displayed, and maybe edited in an html form. Is there anything I can do to convert this string back to the 硼 character in the Java code, or is it perfectly fine to put the HTML String into the database and search on that?

Think about this: if all 硼 characters appear to your application as &#30844, then when your user searches for "硼," your application will see "&#30844." Why would you need to convert it into something human-readable when it's the machine doing the searching?

zootm
Aug 8, 2006

We used to be better friends.
You should probably always be using and storing unescaped text at the back-end and only translating it as you need to in the view. Commons Lang includes StringEscapeUtils which can, among other things, convert from HTML-encoded elements back and forth to plain strings.

Also you don't actually need to entity-encode the character if your output format is UTF-8. I'm afraid I'm not sure what's going on with the form handling in Struts (I really don't miss working with Struts) to get you that stuff back but it's probably standard in some way.

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

capr1ce posted:

What I need to do is store it in a database, and then it needs to be searched against and displayed, and maybe edited in an html form. Is there anything I can do to convert this string back to the 硼 character in the Java code, or is it perfectly fine to put the HTML String into the database and search on that?

Apache has StringEscapeUtils in their Commons Lang package:
http://commons.apache.org/lang/

Specifically, escapeHTML() and unescapeHTML() are what you are looking for.

capr1ce
Oct 30, 2004

Thanks for the replies, I've tried a few things.

csammis, really I need to store the proper text as the data will be coming in from more than one source.

But the StringEscapeUtils class is very helpful! I also found I can get the same affect by setting a property on the html form to tell it to accept UTF-8 as the charset.

StringEscapeUtils converts the HTML entities back to what must be the original characters, but I am getting the following output (in the Eclipse terminal):
硼酸�玻璃

I am assuming this is just Eclipse or Tomcat not being able to display the characters properly, but i've set up the Eclipse workspace to use UTF-8 and also Tomcat. But that hasn't helped. Interestingly if I copy the characters into notepad++ and convert it to UTF-8 it looks mostly like the correct characters with some extra stuff in the middle.

Edit: Ok, I found out how to properly set up Eclipse to show UTF-8 and it's working perfectly. Thanks so much!

capr1ce fucked around with this message at 15:07 on Apr 6, 2009

CT2049
Jul 24, 2007
I'm running into a very specific problem that is a bit of a show stopper for me. For my school I'm writing two very basic into to web development tutorials for teh incoming foreign students. One for ASP.NET with Visual Web Developer 2008 and one for Visual Web JavaServer Face Pages with NetBeans 6.5. Each of these tutorials are being developed in the technology they are teaching so that we can show examples right inside the pages.

I need to display the markup for examples to the user. To do this I'm using a pre HTML element and putting the markup inside there with important characters such as < and > escaped with HTML escape characters. The problem I'm having is displaying markup with a binding attribute such as:
code:
<webuijsf:label binding="#{Page1.nameLabel}" id="nameLabel"/>
Even if I escape the #, {, and } I always get an error saying #{...} are not allowed inside a template text body. Does anyone know what I need to do to display this text as is?

If I'm doing something really stupid feel free to tell me, I've been out of the Java world for a few years now and I'm never worked with Visual Web JavaServer Face Pages technology either.

Warblade
Apr 10, 2003

Beep Beep, Motherfucker!
This question is kind of language agnostic, but I'm dealing with Java so maybe there's some kind of Java convention for doing this. Say you write a class that accepts some kind of listener. At some point you'll be iterating through all of your listeners to notify them that something significant happened. Maybe the method call is listener.sendEvent().

Is there some kind of best practice, or convention for what the sender and receiver should and shouldn't do?

I guess it would be good defensive programming to spawn a worker thread that actually calls listener.sendEvent(). But, as a receiver, should you also strive not to do things like sleeping for some indeterminate amount of time, or is it simply up to the sender to protect itself against that kind of situation?

csammis
Aug 26, 2003

Mental Institution

Warblade posted:

This question is kind of language agnostic, but I'm dealing with Java so maybe there's some kind of Java convention for doing this. Say you write a class that accepts some kind of listener. At some point you'll be iterating through all of your listeners to notify them that something significant happened. Maybe the method call is listener.sendEvent().

Is there some kind of best practice, or convention for what the sender and receiver should and shouldn't do?

I guess it would be good defensive programming to spawn a worker thread that actually calls listener.sendEvent(). But, as a receiver, should you also strive not to do things like sleeping for some indeterminate amount of time, or is it simply up to the sender to protect itself against that kind of situation?

I can't speak for Java, but in the .NET asynchronous model the responsibility for defensive programming rests with the receiver, as it can make no guarantees about the behavior of the sender. The sender should most likely not use a worker thread to raise events, because then the receiver has to contend with events happening out-of-expected-order (or the sender has to ensure that one event has been fully dispatched before raising another).

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Don't fall too quickly into the "defensive coding" trap. It's acceptable to impose rules like listeners should return quickly or else — trust is good unless you're actually hosting external code (e.g. loading user-provided classes).

Anyway, my advice here depends a lot on the nature of your architecture. Do events need to delivered in a strict order? Can multiple events be coalesced into a single event dispatch? Is it okay to deliver spurious/redundant events? How many listeners will a single dispatcher have? Are events fairly self-contained, or are listeners likely to need extra information whenever an event occurs? In general, weakening the constraints on the dispatcher permits faster/more parallel dispatch, but requires more effort in listener implementations.

1337JiveTurkey
Feb 17, 2005

Warblade posted:

This question is kind of language agnostic, but I'm dealing with Java so maybe there's some kind of Java convention for doing this. Say you write a class that accepts some kind of listener. At some point you'll be iterating through all of your listeners to notify them that something significant happened. Maybe the method call is listener.sendEvent().

Is there some kind of best practice, or convention for what the sender and receiver should and shouldn't do?

I guess it would be good defensive programming to spawn a worker thread that actually calls listener.sendEvent(). But, as a receiver, should you also strive not to do things like sleeping for some indeterminate amount of time, or is it simply up to the sender to protect itself against that kind of situation?

All event listeners in Java should derive from the java.util.EventListener interface, and all objects giving the specifics of a certain event should use the java.util.EventObject. Those are more markers than anything else, but they're what everyone expects for typing purposes. The javax.swing.event.EventListenerList can store listeners of multiple different types in one array and returns an iterator of only the type that you want when you pass it the corresponding class object. Normally that's wrapped so that there's a public addFooListener() method which adds a listener, a public removeFooListener() which removes the given listener, a getFooListeners() which returns an array of the registered listeners, and one or more protected fireFoo() methods corresponding to the events which the listeners can receive. These events should normally create a new object of the correct type, initialize it and then send it to all of the listeners. As a rule, the sender owns the event and the receivers shouldn't change it at all but this is by convention so the sender shouldn't create duplicates of any data it sends.

Listeners should generally be quick and return immediately. Quick in GUI terms is actually a surprisingly long period of time, but never block on the event loop. You know when Windows says a program has stopped responding? Dollars to donuts some genius went and did that because no events deposited in the queue by the OS in the last five seconds have been retired. There are methods for only attempting to grab a resource which will just return false if they fail and can be used, but generally anything that needs to wait for something should be spawned off into a separate worker thread while everything else can safely be done in the main event loop.

Two things to pay particular attention for are event loops and cascades where events trigger other events which can lead to a non-local infinite loop or just horrible performance as something gets triggered way too many times. I find that this often happens when there's both a 'real' model and another model which exists solely for the view and the controller and the programmer attempts to synchronize the two through events. Either use the default models to store the real data or wrap the real data structures in the appropriate interfaces in that case.

Finally watch out for keeping references in listeners to other parts of the GUI. It's better to send everything through the associated EventObject so that there aren't any spurious references keeping things from being garbage collected.

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?
What is the feasibility of writing and deploying a java application onto a Trimble unit running Windows Mobile 6. I am writing another GIS system that will have that target platform. I plan on writing it in C#, but I want to investigate further into the possibility of using Java so the code could be multiplatform and possibly incorporate the rest of all our other code (the vast majority of which is in Java).

Basically, I have to justify not using Java.

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?
I'm doing my first semester of Java programming and i have an error that i just cannot figure out for the life of me.

"Exception in thread "main" java.lang.ClassFormatError: Duplicate method name&signature in class file csci1902/lab3/LinkedList$Node"

To me this says that there are at least 2 methods with the same name/signature, but i'm not seeing that anywhere. What am i missing?

I posted my full output at the bottom of the code in comments. Thanks.

http://pastebin.com/m7b75c290

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Something's been miscompiled; try deleting all your class files (not your source files, obviously) and recompiling from scratch. Are you using some alternate compiler?

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?
Thanks for the quick reply. I'm using eclipse btw.

I just saved all the files, deleted all the java files from the package and then created new ones (the same ones) and copied back over. I'm no longer getting that error but now this one:

code:
java.lang.NoClassDefFoundError: LinkedList
Caused by: java.lang.ClassNotFoundException: LinkedList
	at java.net.URLClassLoader$1.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Exception in thread "main" 
How can it not find that class when that is the exact class i'm in when using the my main method?

EDIT:

I'm reading that is has something to do with not being able to find the .class file for LinkedList. However, LinkedList is residing in the same folder as before along with all of my other .java's and .class's.

EDIT: I just deleted the directory of .class's and .java's and then created a new class and new interfaces within eclipse. And now we're back to java.lang.ClassFormatError: Duplicate method name&signature in class file

Awesome.

kingcrimbud fucked around with this message at 18:22 on Apr 9, 2009

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?
Are there errors in this class? I have this class inside of my LinkedList class and i'm guessing that the problem is in here because i can't even instantiate a Node.

code:
private class Node 
	{
		private T data;
		private Node next;
		
		private Node()
		{
			data = null;
			next = null;
		} // end constructor		
		
		private Node(T dataPortion)
		{
			data = dataPortion;
			next = null;
		}// end constructor
		
		private Node(T dataPortion, Node nextNode)
		{
			data = dataPortion;
			next = nextNode;
		}// end constructor
		
		private T getData()
		{
			return data;
		} // end getData
		
		private void setData(T newData)
		{
			data = newData;
		} // end setData
		
		private Node getNextNode()
		{
			return next;
		} // end getNextNode
		
		private void setNextNode(Node nextNode)
		{
			next = nextNode;
		} // end setNextNode
	} // end Node
Within an add method, i'm using the line
Node newNode = new Node(obj);
Which as far as I know should instantiate and put obj in the dataPortion per the second Node constructor.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Your source files are fine; if there were something wrong with your source code, you'd get compiler errors, not runtime errors (modulo a bug in the compiler, which is extremely unlikely if you're using the standard Sun JDK, because the compiler does basically nothing). The runtime system is somehow loading a malformed .class file.

I suspect you've twiddled a few too many knobs in your project configuration. Trying creating a new project and adding the source files to it. If that doesn't work, well, that's what office hours are for.

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?
I threw Node in its own class and that seemed to fix the problem right there.

I guess that was a good example on why to keep classes separate from one another.

Thanks for your help, i'm sure i'll be back later tonight with more questions!

Summit
Mar 6, 2004

David wanted you to have this.
I was gonna say the problem is your constructor is declared private, so it can only be called from within the class... but I'm not sure how that works with a class-within-a-class relationship. Something to try anyway.

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?

Kaltag posted:

What is the feasibility of writing and deploying a java application onto a Trimble unit running Windows Mobile 6. I am writing another GIS system that will have that target platform. I plan on writing it in C#, but I want to investigate further into the possibility of using Java so the code could be multiplatform and possibly incorporate the rest of all our other code (the vast majority of which is in Java).

Basically, I have to justify not using Java.


So I've looked into it and the main issue is getting a good JVM for WM6. The free ones are open source and the others cost money. Does anyone have experience with the wm6 open source jvm? It looks like poo poo on the website.

Jonba
Oct 10, 2004
Tex-Mex Connoisseur
Hey, I have an interesting Swing JTabbedPanes problem.

The way I'm implementing it is that I have a class that extends JFrame. Its constructor adds a JTabbedPane to its contentPane. Then four JPanels are put together (in the same class) and added as tabs to the JTabbedPane.

Here's the weirdness: When clicking on tabs, their contents don't load unless you try to view a tab to the right of it first.

Here's an example:
I run a test to show the JFrame. The first tab loads up fine. I click on the second tab and it doesn't show anything, it's just blank. I click on the third tab and it, too, is blank. Now I go back to the second tab and it loads fine! :raise:

Any ideas? Am I missing something here?

Mill Town
Apr 17, 2006

Jonba posted:

Hey, I have an interesting Swing JTabbedPanes problem.

The way I'm implementing it is that I have a class that extends JFrame. Its constructor adds a JTabbedPane to its contentPane. Then four JPanels are put together (in the same class) and added as tabs to the JTabbedPane.

Here's the weirdness: When clicking on tabs, their contents don't load unless you try to view a tab to the right of it first.

Here's an example:
I run a test to show the JFrame. The first tab loads up fine. I click on the second tab and it doesn't show anything, it's just blank. I click on the third tab and it, too, is blank. Now I go back to the second tab and it loads fine! :raise:

Any ideas? Am I missing something here?

I can't think of anything obvious that would cause that. Post the full code so we can look at it and try it out ourselves.

Flamadiddle
May 9, 2004

So I'm trying to make a bouncing ball simulator. I've managed to make a model but want to represent it graphically. So far I've got the model in one class and the GUI in another. Couple of questions:

1 - To make the physics work I've used Thread.sleep() in a while loop to allow for time-dependent functions. Is this anywhere near the best method? I get the feeling it's not because....

2 - I can't figure out how to pass a real-time height parameter from the bouncing ball procedure to the GUI to represent it.

Any pointers on how this would best be implemented would be appreciated.

ynef
Jun 12, 2002

Flamadiddle posted:

So I'm trying to make a bouncing ball simulator. I've managed to make a model but want to represent it graphically. So far I've got the model in one class and the GUI in another. Couple of questions:

1 - To make the physics work I've used Thread.sleep() in a while loop to allow for time-dependent functions. Is this anywhere near the best method? I get the feeling it's not because....

2 - I can't figure out how to pass a real-time height parameter from the bouncing ball procedure to the GUI to represent it.

Any pointers on how this would best be implemented would be appreciated.

This approach can work. There are alternatives, but let's first study the one you have.

In your current approach, you would have one thread that runs the model, and then you'd have another that manages the GUI. When the GUI thread decides it needs to redraw the scene, it should query the position of the ball from your ball model object (create the ball model object first, then feed the GUI object with a reference to it). However, since you have two threads working with the same data (the position of the ball), you should make sure that your inter-thread concurrency is handled well. Read up on thread concurrency in general, and on the "synchronized" keyword especially.

Another approach is to have only one thread, the GUI thread. The pseudo code for it would be:

code:
while still running:
  startTime = get current time in milliseconds
  ballModel.update(startTime - stopTime)
  // update other stuff
  stopTime = get current time in milliseconds

  // sleep appropriate time to get reasonable FPS, using startTime and stopTime
With this approach, the ball model is fed information about how long ago it was since it was last updated, and can proceed with the simulation accordingly.

Since you already have a working ball simulator, I would suggest that you stick with the first approach, the second one being only for future reference. The more easily you can make use of several threads these days, the better. ;)

[edit] If you want to study this topic further, the phrase to search for is "game loop".

ynef fucked around with this message at 06:25 on Apr 14, 2009

Flamadiddle
May 9, 2004

Awesome. Thanks for the help.

HFX
Nov 29, 2004

ynef posted:

This approach can work. There are alternatives, but let's first study the one you have.

In your current approach, you would have one thread that runs the model, and then you'd have another that manages the GUI. When the GUI thread decides it needs to redraw the scene, it should query the position of the ball from your ball model object (create the ball model object first, then feed the GUI object with a reference to it). However, since you have two threads working with the same data (the position of the ball), you should make sure that your inter-thread concurrency is handled well. Read up on thread concurrency in general, and on the "synchronized" keyword especially.

Another approach is to have only one thread, the GUI thread. The pseudo code for it would be:

code:
while still running:
  startTime = get current time in milliseconds
  ballModel.update(startTime - stopTime)
  // update other stuff
  stopTime = get current time in milliseconds

  // sleep appropriate time to get reasonable FPS, using startTime and stopTime
With this approach, the ball model is fed information about how long ago it was since it was last updated, and can proceed with the simulation accordingly.

Since you already have a working ball simulator, I would suggest that you stick with the first approach, the second one being only for future reference. The more easily you can make use of several threads these days, the better. ;)

[edit] If you want to study this topic further, the phrase to search for is "game loop".

A more interesting option would be have a manager thread. He tell the container the ball is in to update and then passes a reference of the container to the GUI. The gui then asks the container to draw itself to a certain surface. The container tells the ball to draw itself to the reference the container was passed. This gets into a lot of abstraction, but can make an amazing way to add items without worrying about the GUI having to learn to draw new things. The ball of course is actually using a multiple inheritance trick there. One that does ball things, one that does drawable ball things.

HFX fucked around with this message at 20:33 on Apr 14, 2009

w00tz0r
Aug 10, 2006

I'm just so god damn happy.
I'm running FindBugs on some code I'm working on for an assignment, and I can't figure out why I'm getting an error saying "method may fail to close stream on exception".

code:

InputStream inStream;
OutputStream outStream;

inStream = null
outStream = null;

try
{
    //Don't worry about srcFile and outFile, unless for whatever reason you think
    // they're involved. Those two files are created elsewhere.
    inStream  = new BufferedInputStream(new FileInputStream(srcFile));
    outStream = new BufferedOutputStream(new FileOutputStream(outFile));

    bytesRead = inStream.read(buffer, 0, BUFFER_SIZE);

    while (bytesRead > -1)
    {
        bytesRead = inStream.read(buffer, 0, BUFFER_SIZE);
        outStream.write(buffer);
    }
}
// I'm assuming my problem is down here, but I don't see what's wrong.
// It's things like this that make me really love c#'s "using" blocks. :(
finally
{
    if (inStream != null)
    {
        inStream.close();
    }
    
    if (outStream != null)
    {
        outStream.close();
    }
}
I'd really appreciate any sort of pointers as to why I'm getting this error.

zootm
Aug 8, 2006

We used to be better friends.
inStream.close() can throw an exception, which will prevent outStream.close() from being called. This sort of thing is almost always ugly in Java, I think a lot of systems have frameworks to abstract this horribleness away. Something like this might work, though:

code:
final InputStream inStream;
try
{
    inStream  = new BufferedInputStream(new FileInputStream(srcFile));

    final OutputStream outStream;
    try
    {
        outStream = new BufferedOutputStream(new FileOutputStream(outFile));
        bytesRead = inStream.read(buffer, 0, BUFFER_SIZE);

        while (bytesRead > -1)
        {
            bytesRead = inStream.read(buffer, 0, BUFFER_SIZE);
            outStream.write(buffer);
        }
    }
    finally
    {
        outStream.close();
    }
}
finally
{
    inStream.close();
}
It's horrible, though. Alternatively you could have a try/finally in your finally (so you can drive while you drive).

zootm fucked around with this message at 12:02 on Apr 15, 2009

w00tz0r
Aug 10, 2006

I'm just so god damn happy.
Thanks a ton. That's cleared it all up. :)

zootm
Aug 8, 2006

We used to be better friends.
I just realised I have absolutely no idea what happens if the constructors throw exceptions; the null checks might be required regardless, which is even bloody worse...

Warblade
Apr 10, 2003

Beep Beep, Motherfucker!

zootm posted:

It's horrible, though. Alternatively you could have a try/finally in your finally (so you can drive while you drive).

I like putting a try/catch in the finally for closing streams. Except the exception handler doesn't do anything aside from maybe printing out some kind of warning. There's really no way to recover from that. You're closing the stream anyway. Just move on.

zootm posted:

I just realised I have absolutely no idea what happens if the constructors throw exceptions; the null checks might be required regardless, which is even bloody worse...

Yeah, he's going to need those null checks. If the constructors throw an exception its going to look for any exception handlers. There aren't any so that's fine. Then it will execute the finally block. Without the null checks now you've now got some NullPointerExceptions.

Warblade fucked around with this message at 22:04 on Apr 15, 2009

csammis
Aug 26, 2003

Mental Institution

Warblade posted:

I like putting a try/catch in the finally for closing streams. Except the exception handler doesn't do anything aside from maybe printing out some kind of warning. There's really no way to recover from that. You're closing the stream anyway. Just move on.

Which of course begs the question of why streams were engineered to throw exceptions on close in the first place, since you're right and there's basically nothing to be done at that point. This is something I've never figured out for myself but maybe there's a good reason v :) v

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost

csammis posted:

Which of course begs the question of why streams were engineered to throw exceptions on close in the first place, since you're right and there's basically nothing to be done at that point.
For the same reason that open files may not be allowed to close due to locking. You could either signal to another thread or remote process that the file resource should be closed on their end so you can close it, too. It's also possible for some pipes to be really flaky and require multiple closes with some delay in between. See: Windows readlocking horrors.

Sometimes I think monadic I/O is more sane than wrangling ridiculous try/catch/finally blocks that recursive expand into more try/catch/finally blocks.

zootm
Aug 8, 2006

We used to be better friends.

necrobobsledder posted:

Sometimes I think monadic I/O is more sane than wrangling ridiculous try/catch/finally blocks that recursive expand into more try/catch/finally blocks.
Really just being able to aggregate them would be enough. C# has using which sorts this right out. The Automatic Resource Management proposal (i.e. basically the same thing) and the Closures proposal (which would allow you to write the equivalent as a library) have both been refused I think, which isn't encouraging.

1337JiveTurkey
Feb 17, 2005

A using or with block would go a long ways to making that stuff sane. On the plus side it does look like at least the null pointer checks are going to be less painful in Java 7 since they're certain at this point that it'll have the .? short-circuiting dereference operator. istream.?close() would call the method only if the stream isn't null. They'll also add another assignment operator foo ?= bar which assigns bar to foo iff foo is null. Also on the topic of closing streams, they've got some neat new annotations for IDEs that can be added to parameters in method signatures to tell whether stream arguments will be closed at the end of the method call or not.

Warblade
Apr 10, 2003

Beep Beep, Motherfucker!

1337JiveTurkey posted:

A using or with block would go a long ways to making that stuff sane. On the plus side it does look like at least the null pointer checks are going to be less painful in Java 7 since they're certain at this point that it'll have the .? short-circuiting dereference operator. istream.?close() would call the method only if the stream isn't null. They'll also add another assignment operator foo ?= bar which assigns bar to foo iff foo is null. Also on the topic of closing streams, they've got some neat new annotations for IDEs that can be added to parameters in method signatures to tell whether stream arguments will be closed at the end of the method call or not.

That's some nice syntatic sugar. Now I just want Java to introduce unsigned values. Which will probably never happen :(

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

Warblade posted:

That's some nice syntatic sugar. Now I just want Java to introduce unsigned values. Which will probably never happen :(

What's sad is the jvm byte code interpreter actually uses unsigned short integers, and the Oak language (which was basically Java's daddy) had specific mention of allowing unsigned modifiers to integral types. Specifically, from the Oak spec:

quote:

Integer Types
Integers in the Oak language are similar to those in C and C++, with two
exceptions: all integer types are machine independent, and some of the traditional
definitions have been changed to reflect changes in the world since C was introduced. The four integer types have widths of 8, 16, 32, and 64 bits, and are
signed unless prefixed by the unsigned modifier.

but then, sadly, in the sidebar:

quote:

unsigned isn’t implemented yet; it might never be.

gently caress.

1337JiveTurkey
Feb 17, 2005

The lack of unsigned numbers don't bother me too much at least as far as work goes. There's two things which unsigned numbers provide: An implicit lower bound on possible values and twice the number of possible positive values. The implicit lower bound is nice, but it's no substitute for proper bounds checking every input.

The extra positive range is pretty much illusory: If n bits isn't enough n + 1 bits won't be enough in practice. Any company can grow to or churn through 256 employees if they can do 128, and ~2 billion employees isn't any less laughable than ~4 billion. Y2038 fix proposals aren't talking about just using an unsigned number because even if it pushes things back until after almost everyone is dead, 64 bit just isn't that big of a deal these days. When I get an unsigned number smaller than 32 bits in some imported data, treating it as an int for internal calculations doesn't hurt anything as long as I remember its 'real' range for when it counts, such as writing it back out.

Performing arithmetic on numbers that use the extra range is spotty since beyond multiplication possibly causing overflow, now addition and subtraction can as well. Since Java continues on the C tradition of not trapping them and letting the programmer sort it out, it's a whole extra can of worms dumped on top of everything else.

That said, I'm extending an emulator someone wrote for the MIPS architecture to some other ones for fun and it seems like I'm doing a lot of ((long) foo) & 0x00000000FFFFFFFF. It's tedious at points but at least most operations are identical in practice so I can just add, shift or multiply and not give a gently caress since the only difference is the interpretation of the result.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
The only place I ever particularly regret not having unsigned numbers in Java is on bytes, which are just fabulously awkward to work with because of signedness issues.

rjmccall fucked around with this message at 22:54 on Apr 16, 2009

Adbot
ADBOT LOVES YOU

HFX
Nov 29, 2004
I often have to work with implementing network based protocols in Java. Java's lack of unsigned type can make this a lot harder then it should be.

The syntactic sugar isn't a huge bonus to me as I often design my code to prevent the need for such checks except in a few areas.

Items I would like Java to add:

  • Proper tail recursion handled by the VM. I'm a huge fan of functional languages.
  • Operator overloading. This can be terrible or great depending on programmer usage. I have certainly seen it abused.
  • True multiple inheritance so I can quit having to add interfaces which simply invoke a member instance which implements the interface. I guess an IDE could do this automatigically for me though so its not a big issue. Does bring about other issue though.
  • Finally, I'd like a method for notification of a garbage collections. This would allow me to cache unneeded objects in certain data structures and release them if the system needs memory.

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