Enumeration , class
I have this following code in my JSP
Enumeration en = session.getAttributeNames();
System.err.println("Enumeration is "+en.getClass());
gives me "java.util.Vector$1"
Why does it show vector, a lit confused
TIA
Enumeration is an interface.
java.util.Vector$1 is the class that is actually implementing the Enumeration interface.
It is not actually a Vector. The $1 means that this class is actually an anonymous inner class of Vector.
This is the code out of the Vector class that provides the enumeration.
public Enumeration elements() {
return new Enumeration() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
public Object nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData[count++];
throw new NoSuchElementException("Vector Enumeration");
}So you actually do have an object that implements the enumeration interface. It is just an anonymous inner class written inside the Vector class, so its classname displays as java.util.Vector$1.
Does that clear things up?
Cheers,
evnafets
Similar Messages
-
Implementation of Enumeration Class
Can any one tell me that how the Enumeration class is implemented.
Weather it stores the actual object or it just stores the reference for that....?Can any one tell me that how the Enumeration class is
implemented.Just look in the source code. It is available for all the public APIs.
Weather it stores the actual object or it just stores
the reference for that....?Java always store references to objects. -
Revision: 10438
Author: [email protected]
Date: 2009-09-20 13:43:14 -0700 (Sun, 20 Sep 2009)
Log Message:
Add enumeration class for VAST resource type attribute.
Modified Paths:
osmf/trunk/libs/VAST/.flexLibProperties
osmf/trunk/libs/VAST/org/openvideoplayer/vast/model/VASTAdBase.as
osmf/trunk/libs/VAST/org/openvideoplayer/vast/model/VASTTrackingEventType.as
osmf/trunk/libs/VAST/org/openvideoplayer/vast/parser/VASTParser.as
osmf/trunk/libs/VASTTest/org/openvideoplayer/vast/parser/TestVASTParser.as
Added Paths:
osmf/trunk/libs/VAST/org/openvideoplayer/vast/model/VASTResourceType.asRevision: 10438
Author: [email protected]
Date: 2009-09-20 13:43:14 -0700 (Sun, 20 Sep 2009)
Log Message:
Add enumeration class for VAST resource type attribute.
Modified Paths:
osmf/trunk/libs/VAST/.flexLibProperties
osmf/trunk/libs/VAST/org/openvideoplayer/vast/model/VASTAdBase.as
osmf/trunk/libs/VAST/org/openvideoplayer/vast/model/VASTTrackingEventType.as
osmf/trunk/libs/VAST/org/openvideoplayer/vast/parser/VASTParser.as
osmf/trunk/libs/VASTTest/org/openvideoplayer/vast/parser/TestVASTParser.as
Added Paths:
osmf/trunk/libs/VAST/org/openvideoplayer/vast/model/VASTResourceType.as -
****Implementing Enumeration Interface****
I need to implement the enumeration interface in a class which represents a day of the week. I need to be able to call the nextElement method to return the next day in the week. For example, if the current day object is Saturday, the nextElement method should return a Sunday day object. I'm not sure how to implement the hasMoreElements method either. Can anyone help me with the implementation of these two methods? Thanks!
import java.util.Enumeration;
class Day {
int dayNumber;
String dayOfWeek;
Day(int d){
dayNumber = d;
dayOfWeek = new String();
public int getDayNumber(){
return dayNumber;
public String toString(){
switch (dayNumber){
case(0):
dayOfWeek = "Sunday";
break;
case(1):
dayOfWeek = "Monday";
break;
case(2):
dayOfWeek = "Tuesday";
break;
case(3):
dayOfWeek = "Wednesday";
break;
case(4):
dayOfWeek = "Thursday";
break;
case(5):
dayOfWeek = "Friday";
break;
case(6):
dayOfWeek = "Saturday";
break;
default:
dayOfWeek = "number out of bounds";
return dayOfWeek;
public Object nextElement(){
public boolean hasMoreElements(){
}Here is a class tester:
class DayDriver{
public static void main(String args[]){
Day day1, day2;
day1 = new Day(3);
day2 = new Day(0);
System.out.println("day1 = " + day1);
System.out.println("day2 = " + day2);
day1 = (Day)day1.nextElement();
System.out.println("day1's value is " + day1.getDayNumber());
int cnt = 1;
while(day2.hasMoreElements() && cnt<=7){
System.out.println(day2.nextElement());
day2 = (Day)day2.nextElement();
cnt++;
System.out.println(day1.addDays(23) + " is 23 days from a " + day1);
}I am not sure where you would use a class like this. I tried to use the code you provided. I hope it helps.
Day class
import java.util.Enumeration;
public class Day implements Enumeration {
/*=**********
* constants *
public static final String[] DAYS = {"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"};
/*=*************
* data members *
private int startDay;
private int currentDay;
/*=************
* constructor *
public Day(int d)
{ setDay(d); }
/*=************
* get methods *
public int getDayNumber()
{ return startDay; }
/*=************
* set methods *
public void setDay(int d) {
if (d < 0 || d > 6)
startDay = 0;
else
startDay = d;
currentDay = startDay;
}//end setDay method
/*=**********
* addDays() *
public Day addDays(int d) {
int newDay = (startDay + d) % 7;
return new Day(newDay);
}//end addDays method
/*=***********
* toString() *
public String toString()
{ return DAYS[startDay]; }
/*=**************
* nextElement() *
public Object nextElement(){
return new Day(++currentDay);
}//end nextElement method
/*=******************
* hasMoreElements() *
public boolean hasMoreElements(){
boolean result = false;
if (currentDay < DAYS.length) result = true;
return result;
}//end hasMoreElements method
}//end Day class
DayDriver class
public class DayDriver {
/*=*************
* main program *
public static void main(String args[]){
Day day1, day2;
day1 = new Day(3);
day2 = new Day(0);
System.out.println("day1 = " + day1);
System.out.println("day2 = " + day2);
day1 = (Day)day1.nextElement();
System.out.println("day1's value is " + day1.getDayNumber());
int cnt = 1;
while(day2.hasMoreElements() && cnt<=7){
System.out.println(day2.nextElement());
day2 = (Day)day2.nextElement();
cnt++;
System.out.println(day1.addDays(23) + " is 23 days from a " + day1);
}//end main program
}//end DayDriver classTJJ -
BindingException - Invalid Class Received
Hello friends -
I'm currently getting the following error at servicegen ant time:
weblogic.xml.schema.binding.BindingExceptio
n: Invalid class received: interface java.util.Enumeration loaded from file:/C:/bea/jdk1
41_05/jre/lib/rt.jar!/java/util/Enumeration.class. All classes that will be serialized
or deserialized must be non-interface, non-abstract classes that provide a public default constructor
I've done some reading, but most of what I find seems to indicate that this is an issue with wanting to return an unserializable object type from a web service. In my case, I simply want to use a Properties object inside of my web service to retrieve values that would be useful to change without a recompilation. My input and output do not include Enumeration type objects. If I modify my methods to use hardcoded values instead of opening a file using Properties, servicegen will compile the web service fine.
I've also seen some postings indicating this could be a classpath related issue, but have yet to make progress on that end either.
Is it impossible to use / reference any object which does not implement serializable within a web service, even if your input or return types do not utilize these objects?
Any and all guidance is appreciated.
Thanks!
cmI think it is too late to respond but this is what i relize at this point.I am getting the same error but with java.util.Map the reason is these are not supported data types by servicegen so you need to write a data type.Please let me know if you resolved this issue if so How?
-
Accessing 1.5 enumerations from JNI
How do you access a Java 1.5 enumeration from JNI? For example, given
enum Foo { BAR, BAZ };and a call to a native method of the form
someObject.callSomeNativeMethod(Foo.BAR);How do I find out from the JNI code which member of the enumeration has been passed to it?Seing as nobody answered this, I'll answer it myself. If you use javap -s you can see that each enumeration member ends up as a public static final instance of the enumeration class:
public static final Foo Bar;
Signature: LFoo;I hereby award all the duke dollars to myself. -
Hi,
I was using the Enumeration class to display data that were collected from a previous webpage (just a html page). What sorting mechanism does the Enumeration class use? As the data displayed on the screen was not sorted by the parameters' names or the layout/position of the data elements from the previous page. Thank you.Hi,
I was using the Enumeration class to display data
that were collected from a previous webpage (just a
html page). What sorting mechanism does the
Enumeration class use? As the data displayed on the
screen was not sorted by the parameters' names or the
layout/position of the data elements from the
previous page. Thank you.1st, Enumeration is an Interface, not a class.
2nd, The specific ordering of the Enumeration will depend on the implementation and the source of the Enumeration... if there is one.
If the enumeration comes from a HashMap (for example) then there is no ordering of the enumerator, as there is no order to the HashMap. From a TreeMap, or a SortedSet, then the order of the enumeration comes from the order imposed by the natural ordering of the Map/Set... If the Enumeration comes from a Vector or some other List, the enumeration should be assumed to be the order that the values where inserted in the List...
Without any information on the source of the Enumeration, you should assume that there is no order, and that consecutive calls to the enumeration may result in different order of enumeration. -
AppleScript Class recognition and Array count
I have an application "SolarMaxOsX" written in Obj C
This app is scriptable
I have a class named Ups and in Ups.m I have written following methods:
- (id)init {
self = [super init];
NSLog(@"Init Ups at %p", self);
self.upsName = [NSString stringWithFormat:@"S2000"];
// upsPort = [NSNumber numberWithInteger:1];
self.upsPort = 1;
self.upsIpAddress= [NSString stringWithFormat:@"192.168.10.101"];
self.upsDataListToDisplayInTable = [self fillUpsListDictionary];
_uniqueID = [[NSUUID UUID] UUIDString];
return self;
/* For appleScript recognition */
- (BOOL)application: (NSApplication *) sender delegateHandlesKey:(NSString *)key {
if ([key isEqualToString: @"Ups"]) return YES;
if ([key isEqualToString: @"upsDescriptionDict"]) return YES;
if ([key isEqualToString: @"networkStatus"]) return YES;
if ([key isEqualToString: @"networkOk"]) return YES;
return NO;
- (NSUniqueIDSpecifier *)objectSpecifier {
NSScriptClassDescription *appDescription = (NSScriptClassDescription *)[NSApp classDescription];
return [[NSUniqueIDSpecifier alloc] initWithContainerClassDescription:appDescription containerSpecifier:nil key:@"Ups" uniqueID:self.uniqueID];
In AppDelegate.m:
There is an array : Upss declared as follows:
NSArray (Upss *) Ups; declared and initialised in AppDelegate.m file
self.Upss = [self initUpss];
sdef file for SolarMax Suite follows (compiles correctly)
<suite name="SolarMax Suite" code="SMap" description="Apple Events supportés par l'application SolarMaxMain">
<class name="Ups" code="SCup" description="An object UPS in SolarMaxOsX." >
<cocoa class="Ups" inherits="item" plural="Upss"/>
<property name="id" code="ID " type="text" access="r" description="The unique identifier of the note.">
<cocoa key="uniqueID"/>
</property>
</class>
<element description="List of Ups" type="Ups">
<cocoa key="Upss"/>
</element>
<class name="AppDelegate" code="SCad" description="main class in SolarMaxOsX.">
<cocoa class="AppDelegate" />
// Liste des Ups reconnus dans le fichier de configuration
<property name="Upss" code="SMno" type="Ups" access="r">
<cocoa key="Upss"/>
</property>
</class>
</suite>
I want to get a count for array Upss
Script follows
tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmtiegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app" to activate
-- delay 30
tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmtiegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app"
-- set nomAppli to the name of application
-- set theWindows to windows
set NbWin to the count of windows
set theWindow to first item of windows
properties of the theWindow
tell window "UPS Sumary"
--click on "Statistics button"
-- click on button 1 of theWindow
-- set enabled of button1 to true
end tell
--class of Upss
count of Upss
end tell
I get the following answers:
tell application "SolarMaxOsX"
activate
count every window of current application
--> 1
get item 1 of every window
--> window id 3113
get properties of window id 3113
--> {closeable:true, zoomed:false, class:window, index:1, visible:true, name:"UPS Sumary", miniaturizable:true, id:3113, miniaturized:false, resizable:true, bounds:{1485, 31, 1985, 579}, zoomable:true}
count every Ups of current application
--> error number -1728
Résultat :
error "Erreur dans SolarMaxOsX : Il est impossible d’obtenir every Ups." number -1728 from every Ups
What do I have missed ?
Logiciel OS X 10.9.5 (13F34) (Mavericks)
Xcode Version 6.1 (6A1052d)
Éditeur AppleScript Version 2.6.1 (152.1)
AppleScript 2.3.2Hi Hiroto
It is much better thanks
Now count of onduleurs works
Hi Hiro,
It is much better Thanks for your help
Now, count od onduleurs works
tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmt iegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app" to activate
-- delay 30
tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmt iegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app"
-- set nomAppli to the name of application
-- set theWindows to windows
class of onduleurs
count of onduleurs
-- get properties
set NbWin to the count of windows
set theWindow to first item of windows
properties of the theWindow
tell window "UPS Sumary"
--click on "Statistics button"
-- click on button 1 of theWindow
-- set enabled of button1 to true
end tell
get properties
get id of first onduleur of onduleurs
The results in appleScript:
tell application "SolarMaxOsX"
activate
get class of every onduleur
--> {onduleur, onduleur, onduleur}
count every onduleur of current application
--> 3
count every window of current application
--> 1
get item 1 of every window
--> window id 9796
get properties of window id 9796
--> {closeable:true, zoomed:false, class:window, index:1, visible:true, name:"UPS Sumary", miniaturizable:true, id:9796, miniaturized:false, resizable:true, bounds:{30, 28, 530, 576}, zoomable:true}
get properties
--> error number -10000
Résultat :
error "Erreur dans SolarMaxOsX : Le gestionnaire AppleEvent a échoué." number -10000
And the results of my logging in Objective C debugger:
My sdef file
2014-12-01 23:56:36.040 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
2014-12-01 23:56:36.040 SolarMaxOsX[37551:303] handles onduleursArray OK
2014-12-01 23:56:36.041 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
2014-12-01 23:56:36.041 SolarMaxOsX[37551:303] handles onduleursArray OK
2014-12-01 23:56:36.042 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
2014-12-01 23:56:36.042 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
2014-12-01 23:56:36.043 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
2014-12-01 23:56:36.043 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles scriptingProperties
2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles classCode
2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] handles onduleursArray OK
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles terminologyVersion
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles version
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles name
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles isActive
2014-12-01 23:56:36.046 SolarMaxOsX[37551:303] An exception was thrown during execution of an NSScriptCommand...
2014-12-01 23:56:36.046 SolarMaxOsX[37551:303] Error while returning the result of a script command: the result object...
classCode = 1667330160;
isActive = 1;
name = SolarMaxOsX;
onduleursArray = (
"<Ups: 0x6000002c0bd0>",
"<Ups: 0x6100002c24c0>",
"<Ups: 0x6000000df100>"
terminologyVersion = 1;
version = "1.1";
...could not be converted to an Apple event descriptor of type 'application properties'. The 'onduleursArray' entry could not be converted to an Apple event descriptor of type 'onduleur'. This instance of the class '__NSArrayM' returned nil when sent -objectSpecifier (is it not overridden?) and there is no coercible type declared for the scripting class 'onduleur'.
It seems that my objectSpecifier method in Ups Category (or Ups class) is never called
My sdef File:
<!-- Suite Solar Max -->
<suite name="SolarMax Suite" code="SMap" description="Apple Events supportés par SolarMaxOsX">
<!-- suppress warning for missing "savable file format" type -->
<enumeration name="savable file format" code = "savf" hidden="yes">
<enumerator name= "dummy" code="VTdm"
description="A dummy file format."/>
</enumeration>
<class name="application" code="capp" description="SolarMaxOsX’s top level scripting object." plural="applications" inherits="application">
<cocoa class="NSApplication"/>
<element type="onduleur" access="r">
<cocoa key="onduleursArray"/>
</element>
<property name="onduleurs" code="SMor" description="Array of onduleurs." access="r">
<type type="onduleur" list="yes"/>
<cocoa key="onduleursArray"/>
</property>
<property name="name" code="pnam" description="The name of the application." type="text" access="r"/>
<property name="frontmost" code="pisf" description="Is this the frontmost (active) application?" type="boolean" access="r">
<cocoa key="isActive"/>
</property>
<property name="version" code="vers" description="The version of the application." type="text" access="r"/>
<property name="terminology version" code="TEvn" type="integer" access="r">
<cocoa key="terminologyVersion"/>
</property>
</class>
<class name="onduleur" code="SCup" description="An object onduleur in SolarMaxOsX." plural="onduleurs">
<cocoa class="Ups" inherits="item" />
<property name="id" code="ID " type="text" access="r" description="The unique identifier of the onduleur">
<cocoa key="uniqueID"/>
</property>
<property name="OnduleurName" code="pnam" description="The onduleur name. ." type="text">
<cocoa key="name"/>
</property>
</class>
// Class SolarMaxOsX to access to first window
<class name="SolarMaxOsX" code="SMos" description="main window in SolarMaxOsX.">
<cocoa class="SolarMaxOsX" />
</class>
</suite>
Categories for all classes in he same file: AppDelegate+AppleScriptExtensions.m (category file)
// SolarMaxOsX+AppleScriptExtensions.m
// SolarMaxOsX
// Created by Guy DESBIEF on 28/11/2014.
#import "AppDelegate+AppleScriptExtensions.h"
#import "Ups.h"
@implementation NSObject (MNscriptability)
- (void) returnError:(int)n string:(NSString*)s {
NSScriptCommand* c = [NSScriptCommand currentCommand];
[c setScriptErrorNumber:n];
if (s)
[c setScriptErrorString:s];
@end
@implementation AppDelegate (AppleScriptExtensions)
#define APPLESCRIPT_TERMINOLOGY_VERSION 1
#pragma mark ACCESSOR METHODS
-(NSNumber *) terminologyVersion {
return [NSNumber numberWithInt:APPLESCRIPT_TERMINOLOGY_VERSION];
// For appleScript recognition
-(NSUInteger) countOfOnduleursArray
MyLog(@"countOfOnduleursArray");
return [self.onduleursArray count];
- (Ups *) objectInOnduleursArrayAtIndex : (int) index {
MyLog(@"objectInOnduleursArrayAtIndex %index", index);
Ups *upsItem = [self.onduleursArray objectAtIndex:index];
if (upsItem != nil)
return upsItem;
} return nil;
- (Ups *) valueInOnduleursArrayAtIndex:(unsigned int)i {
MyLog(@"valueInOnduleursArrayAtIndex %i", i);
if (![[NSScriptCommand currentCommand] isKindOfClass:[NSExistsCommand class]])
if (i >= [onduleursArray count]) {
[self returnError:errAENoSuchObject string:@"No such Ups."];
return nil;
MyLog(@"valueInOnduleursArrayAtIndex index OK: %i", i);
return [onduleursArray objectAtIndex: i];
- (BOOL)application: (NSApplication *) sender delegateHandlesKey:(NSString *)key {
MyLog(@"Appdelegate handles %@",key);
if ([key isEqualToString: @"terminologyVersion"]) return YES;
if ([key isEqualToString: @"onduleursArray"]) {
MyLog(@"handles %@ OK",key);
return YES;
return NO;
@end
@implementation Ups (AppleScriptExtensions)
- (NSUniqueIDSpecifier *) objectSpecifier
MyLog(@"objectSpecifier (UPS) OK");
return [[NSUniqueIDSpecifier allocWithZone:[self zone]]
initWithContainerClassDescription: (NSScriptClassDescription *)[NSApp classDescription]
containerSpecifier: nil
key: @"onduleursArray"
uniqueID: uniqueID];
@end
AppDelegate+AppleScriptExtensions.h (category file)
// SolarMaxOsX+AppleScriptExtensions.h
// SolarMaxOsX
// Created by Guy DESBIEF on 28/11/2014.
#import <Foundation/Foundation.h>
#import "AppDelegate.h"
@class AppDelegate;
@class Ups;
@interface NSObject (MNscriptability)
- (void) returnError:(int)n string:(NSString*)s;
@end
@interface AppDelegate (AppleScriptExtensions)
#ifdef NDEBUG
#define MyLog(f, ...)
#else
#define MyLog(f, ...) NSLog(f, ## __VA_ARGS__)
#endif
- (BOOL)application: (NSApplication *) sender delegateHandlesKey:(NSString *)key;
- (NSUInteger) countOfOnduleursArray; -
Hi all
I have a question about enumerations,
class Test{
public enum Gender{
Male, Female
@Enumerated(EnumType.STRING)
@Column(length=1)
private Gender gender;
}my question is this correct?
my goal is to keep only one character of the enumration
thanks for helpHi guys,
here is what I did according to your suggestions
package com.entities;
import com.enumeration.Gender;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
@Entity
@NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name="nom", length=30)
private String nom;
@Enumerated(EnumType.STRING)
@Column(length=1)
private Gender gender;
public Integer getId() {
return id;
public void setId(Integer id) {
this.id = id;
public String getNom() {
return nom;
public void setNom(String nom) {
this.nom = nom;
public Gender getGender() {
return gender;
public void setGender(Gender gender) {
this.gender = gender;
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
@Override
public boolean equals(Object object) {
if (!(object instanceof Employee)) {
return false;
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
return true;
@Override
public String toString() {
return "com.entities.Employee[ id=" + id + " ]";
package com.enumeration;
public enum Gender {
M("Male"), F("Female");
private String description;
private Gender(String description) {
this.description = description;
public String getDescription() {
return description;
}and it generates the table employee with the gender column as a varchar(1) witch is the desired result
thanks a million for help
best regards rashid -
Enumeration and what it means to you.
What is enumeration, and how does it affect your everyday life?
Let me count the ways...
The java Enumeration class is used for things that that can enumerate
themselves - as described here:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Iterator.html
Iterator and Iterable are more useful as described here:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterable.html
The use of collections generally is described in the Tutorial:
http://java.sun.com/docs/books/tutorial/collections/index.html -
Vector collection - enumeration question
Hi all
Question: This is how I currently loop through a Vectors elements:
for (int i = 0; i < clinicVector.size(); i++)
cmbClinic.addItem(((ClinicRecord)clinicVector.elementAt(i)).GetString());
This code simply adds some data from the ClinicRecord class to a Choice component. Now my question is this...is this the fastest way to do this? Or would using the Enumeration class be faster?
Also, I am using JDK1.1.8. Is Vector my only choice for a dynamic collection? I have heard of ArrayList but can't find it in the javadocs (I assume it came in with JDK1.2).
Thanks for any pointers.Let me detail how my system works. You are correct about the ClinicRecord class...it is a wrapper for a table in my back-end DB.
Each field in the tblClinic table has the name of the clinic + an ID (and some other stuff thats not worth mentioning).
As I need to do some matching I have encapuslated my Vector in another object called clinics to take care of this matching (matching from id's to clinic names and vice versa).
My clients (psion netBooks) need to be able to work off-line, so the user has a transfer screen where they can download patients AND what I call lookup objects (Clinic class is one of these). As clinics may have been added by the DBA since the last download, lookup objects are downloaded each time (actually they're not...there is a tick-box on the transfer screen called "Download Lookups...if ticked, downloads them). Lookup objects are persistant objects that get saved to the local client and therefore can be accessed off-line by simply opening from disk.
Sound good? I haven't really given it that much thought. How do you deal with such lookup objects? -
while using vectors why enumeration is done?
Are you asking why Sun provided the Enumeration class?
If so, I always tend to think in terms of substitutability. The Enumeration and Iterator interfaces provide a standardised way to iterate over the members of a collection. Thus the impact on other code of changing the type of the collection used may be minimised.
PS Agree with the previous poster. Unless you need to thread safe features of the Vector, why use it? -
How to set the background for all components?
hi
Does anybody know how to set the DEFAULT background color in an application.. I need it because in jdk 1.3 the default bgcolor is grey and in 1.5 it is white.. and I wish white as well.. so to make it also white in jdk 1.3 I need to use the (a bit annoying) anyContainer.setBackground( Color.white ); and these are lots in my app.. So my question is: is there such an overall class with a function (say UIManager.setComponentsBackground( Color color ) ) for such a purpose?
any tip or link would be greatly appreciatedDoes anybody know how to set the DEFAULT background color in an applicationthis might get you close
import java.awt.*;
import javax.swing.*;
import java.util.Enumeration;
class ApplicationColor extends JFrame
public ApplicationColor()
setApplicationColor(Color.RED);
setLocation(400,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel jp = new JPanel(new BorderLayout());
jp.add(new JTextField("I'm a textfield"),BorderLayout.NORTH);
jp.add(new JComboBox(new String[]{"abc","123"}),BorderLayout.CENTER);
jp.add(new JButton("I'm a button"),BorderLayout.SOUTH);
getContentPane().add(jp);
pack();
public void setApplicationColor(Color color)
Enumeration enum = UIManager.getDefaults().keys();
while(enum.hasMoreElements())
Object key = enum.nextElement();
Object value = UIManager.get(key);
if (value instanceof Color)
if(((String)key).indexOf("background") > -1)
UIManager.put(key, color);
public static void main(String[] args){new ApplicationColor().setVisible(true);}
} -
Reading strings and integers from a text file
I want to read the contents of a text file and print them to screen, but am having problems reading integers. The file contains employee's personal info and basically looks like this:
Warren Laing
32 //age, data type is int
M //gender, data type is String
Sharon Smith
44
F
Here's what I've done so far. The method should continue reading the file until there's no lines left. When I call it from main, I get a numberFormatException error. I'm not sure why because the data types of the set and get methods are correct, the right packages have been imported, and I'm sure I've used Integer.parseInt() correctly (if not, pls let me know). Can anyone suggest why I'm getting errors, or where my code is going wrong?
many thanks
Chris
public void readFile() throws IOException{
BufferedReader read = new BufferedReader(new FileReader("personal.txt"));
int age = 0;
String input = "";
input = read.readLine();
while (input != null){
setName(input);
age = Integer.parseInt(input);
setAge(age);
input = read.readLine();
setGender(input);
System.out.println("Name: " + getName() + " Age: " + getAge() + " Gender: " + getGender());
read.close();To answer your question - I'm teaching myself java and I haven't covered enumeration classes yet.
With the setGender("Q") scenario, the data in the text file has already been validated by other methods before being written to the file. Anyway I worked out my problems were caused by "input = read.readLine()" being in the wrong places. The code below works fine though I've left out the set and get methods for the time being.
Chris
public static void readFile()throws IOException{
String name = "";
String gender = "";
int age = 0;
BufferedReader read = new BufferedReader(new FileReader("myfile.txt"));
String input = read.readLine();
while(input != null){
name = input;
input = read.readLine();
gender = input;
input = read.readLine();
age = Integer.parseInt(input);
input = read.readLine();
System.out.println("Name: " + name + " Gender: " + gender + " Age: " + age);
read.close(); -
Use LINQ to extract the data from a file...
Hi,
I have created a Subprocedure CreateEventList
which populates an EventsComboBox
with a current day's events (if any).
I need to store the events in a generic List communityEvents
which is a collection of
communityEvent
objects. This List needs to be created and assigned to the instance variable
communityEvents.
This method should call helper method ExtractData
which will use LINQ to extract the data from my file.
The specified day is the date selected on the calendar control. This method will be called from the CreateEventList.
This method should clear all data from List communityEvents.
A LINQ
query that creates CommunityEvent
objects should select the events scheduled for selected
day from the file. The selected events should be added to List
communityEvents.
See code below.
Thanks,
public class CommunityEvent
private int day;
public int Day
get
return day;
set
day = value;
private string time;
public string Time
get
return time;
set
time = value;
private decimal price;
public decimal Price
get
return price;
set
price = value;
private string name;
public string Name
get
return name;
set
name = value;
private string description;
public string Description
get
return description;
set
description = value;
private void eventComboBox_SelectedIndexChanged(object sender, EventArgs e)
if (eventComboBox.SelectedIndex == 0)
descriptionTextBox.Text = "2.30PM. Price 12.50. Take part in creating various types of Arts & Crafts at this fair.";
if (eventComboBox.SelectedIndex == 1)
descriptionTextBox.Text = "4.30PM. Price 00.00. Take part in cleaning the local Park.";
if (eventComboBox.SelectedIndex == 2)
descriptionTextBox.Text = "1.30PM. Price 10.00. Take part in selling goods.";
if (eventComboBox.SelectedIndex == 3)
descriptionTextBox.Text = "12.30PM. Price 10.00. Take part in a game of rounders in the local Park.";
if (eventComboBox.SelectedIndex == 4)
descriptionTextBox.Text = "11.30PM. Price 15.00. Take part in an Egg & Spoon Race in the local Park";
if (eventComboBox.SelectedIndex == 5)
descriptionTextBox.Text = "No Events today.";Any help here would be great.
Look, you have to make the file a XML file type -- Somefilename.xml.
http://www.xmlfiles.com/xml/xml_intro.asp
You can use NotePad XML to make the XML and save the text file.
http://support.microsoft.com/kb/296560
Or you can just use Notepad (standard), if you know the basics of how to create XML, which is just text data that can created and saved in a text file, which, represents data.
http://www.codeproject.com/Tips/522456/Reading-XML-using-LINQ
You can do a (select new CommunityEvent) just like the example is doing a
select new FileToWatch and load the XML data into the CommunityEvent properties.
So you need to learn how to make a manual XML textfile with XML data in it, and you need to learn how to use LINQ to read the XML. Linq is not going to work against some flat text file you created. There are plenty of examples out on Bing and Google
on how to use Linq-2-XML.
http://en.wikipedia.org/wiki/Language_Integrated_Query
<copied>
LINQ extends the language by the addition of query
expressions, which are akin to
SQL statements, and can be used to conveniently extract and process data from
arrays, enumerable
classes, XML documents,
relational databases, and third-party data sources. Other uses, which utilize query expressions as a general framework for readably composing arbitrary computations, include the construction of event handlers<sup class="reference" id="cite_ref-reactive_2-0">[2]</sup>
or
monadic parsers.<sup class="reference" id="cite_ref-parscomb_3-0">[3]</sup>
<end>
<sup class="reference" id="cite_ref-parscomb_3-0"></sup>
Maybe you are looking for
-
My family uses a single lap-top as our home computer and several of us have i-pods that we like to synch, using I-tunes. Although we've tried to create separate I-tune accounts, our i-tunes playlists are getting wiped out when one of us deletes song
-
What's wrong with Siri on iOS7? It does not find all of my contacts
I am trying to call somebody with Siri and it tells me it cannot find that person on my contacts even when it's there, does anybody have the same issue? DO you know what's wrong? or how can we fix it? Thank you.
-
Corruption of owner admin acct.
I suddenly became unable to complete opening any of my Adobe software. Re-installing didn't help. I got an error message when trying to install new ISP software that I did not have admin. status. I created a new acct. to which I granted admin. permis
-
MIDI Drums not syncing with tempo track automation
I created some tempo changes, basically subtle speed-ups etc, worked fine, recorded guitars and bass, made a rough mix, all sounded great. Now I go back to do more recording and editing, and the MIDI drums won't speed up with the automation, thus put
-
EEM Scripting for error and drop counters
Hi, We want to check the following counters for drops every 5 minutes and generate an alarm if a certain threshold of errors (example: increment of 100 in the error/drop counters in the last 5 minutes) is overcome: My sample script is inline, i'm mis