Custom Deserialization for a List of serializable objects
I'm running into trouble creating custom deserialization using the readObject method.
Here is the code the reads the blob from the database:
Blob blob = rs.getBlob(idx++);
InputStream iStream = blob.getBinaryStream();
try {
ObjectInputStream oiStream = new ObjectInputStream(iStream);
Object object = oiStream.readObject();
List data = (List) object;
report.setData(data);
catch (EOFException ignored) {}
finally {
iStream.close();
}And my class:
public class PerformanceReportRowInfo extends PerformanceInfo
private static final long serialVersionUID = 20060406L;
private String _dateStr;
private long _queries;
private void readObject (ObjectInputStream ois) throws IOException,
ClassNotFoundException
ObjectInputStream.GetField fields = ois.readFields();
_dateStr = (String) fields.get("_dateStr", null);
try {
_queries = fields.get("_queries", 0L);
} catch (IOException io) {
int intQueries = fields.get("_queries", 0);
_queries = (long) intQueries;
}The reason custom deserialization is needed is because we are converting the "_queries" attribute from an int to a long, and do not want to have to replace all the blobs in our DB with long types.
For some reason, however, the readObject method never gets called in the PerformanceReportRowInfo, and instead i continue to get the error message:
java.io.InvalidClassException: PerformanceReportRowInfo; incompatible types for field _queries
I even added logging to the readObject method to make sure it wasnt getting called, and my suspicion was confirmed, it was indeed not getting called. Is my problem related to the fact that it is extending another serializable object (in this case PerformanceInfo) that doesnt have a custom readObject method? Or is it because of how im converting the blob to a List in the first block of code? BTW, the exception occurs at this line:
Object object = oiStream.readObject();
Thanks for the help!
It is Serializable and does not extend any other class (except Object of course), here is the full stack trace:
Caused by: java.io.InvalidClassException: PerformanceReportRowInfo; incompatible types for field _queries
at java.io.ObjectStreamClass.matchFields(ObjectStreamClass.java:2175)
at java.io.ObjectStreamClass.getReflector(ObjectStreamClass.java:2070)
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:586)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1552)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1552)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at java.util.ArrayList.readObject(ArrayList.java:591)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:946)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1809)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at MyClass.readReport(MyClass.java:332)
Similar Messages
-
Custom layout for product list view
Hi all,
Can I create a template .tpl that is assigned only to either the product detail or list view?......or has any created a workaround for this below?
I want to display a list of products in a particular category, with a sub-menu down the left hand side of the page, but the detail view of the individual product to be across the full page width. I have several categories each with it's own sub-menu ( for the side).
I currently have a few templates, containing the various side menus, formatted to display as I need, but of course, this layout gets assigned also to the detail view, which is what I don't want.
Would be great to see other ideas.
Thanks in advance. DCThanks Liam,
Do you have any info on when this might be happening? Hoping to have this site completed in 2 weeks. Best workaround option atm is to have separate pages ( with their custom side menus) with individually tagged products displayed. The detail view for the product can then have the full width view. - Bit of a long winded way around, but I don't see any other option if this is the desired result. -
Custom Layout for FBL1N (Open Vendor Items)
Hi All,
I would like to create a custom layout for the List Output. Currently there is only options as to display the Standard Local currency, I would like to include the value for the Document Currency (Transaction Currency) as well. Does anyone have come across this before? Thanks.
Thanks.Hi,
Creating a layout for any report is very easy.
Go to TCODE FBL1N, in the output screen, below the menu options, you will find few buttons. you will find the button select layout, click on any one layout, and then click on the button select fields and copy the hidden fields from the select fields option, add the fields you wish to add and then save the layout with a new name. Or you can also go through menu options - Settings ==> Special Fields - Include your special fields from the available tables. (This is cross client configuraiton)
hope this helps
regards,
radhika -
Concurrent timers are not getting invoked for same timer info (Serializable
Problem Scope: Concurrent timers are not getting invoked for same timer info (Serializable object containing the details of timer).
Details : I am implementing EJB timer 2.1 and when ejbTimeOut execution of one timer exceeds the interval time, next timeout doesnt happens till the execution of first ejbTimeOut completes . Ideally the timers should behave in the manner that on every interval the ejbTimeOut should occur no matter the previous timeout is completed or not
for example : consider there is timer T whose timeout occurs every minute, and on every timeout it calls process P, so on every minute ideally container should give call to process P irrespective of the previous status of P (call is complete or not). In our case next call to process P is not happening after timeout also since it is waiting for previous call to P to get completedYou should also cross-post this in the WebLogic EJB forum:
WebLogic Server - EJB -
Delete authorization for distribution list
Hi,
In our system all the distribution lists suddenly deleted and it was in the shared trash folder.
so we retrived from the folder.
To restrict the delete authorization of users for distribution lists in the object S_OC_ROLE field OFFADMI ' Administrator' has been changed to ' '. But they were not able to create the the distribution list in the shared folder. they are able to create only in their private folder.
Is there any way to restrict the delete authorization alone.
Thanks,
SuganyaHi Stef,
Please try to add this authorisation object manually F_BKPF_BUK- Authorisation object for company code.
In the filed BUKRS you can maintain the company code as you required for the users.
I hope this may help you in resolving the issue.
Thanks
Karthick -
"ClassCastException" for items in List after serialization
consider this code:
public class MyClass implements Serializable {
public double price = -1;
public double volume = -1;
List list = new ArrayList<MyClass>();
while(!endOfData) {
MyClass mc = new MyClass();
mc.price = x;
mc.volume = y;
list.add(mc);
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(list);----
and then the receiver-side:
ObjectInputStream ois = new ObjectInputStream(in);
List list = (List) ois.readObject();
MyClass mc = (MyClass) list.get(2);
..... error ... error ...
Exception in thread "Thread-1" java.lang.ClassCastException: MyClass
note: using a Double instead of MyClass works ok.
also please notice:
ObjectInputStream ois = new ObjectInputStream(in);
List list = (List) ois.readObject();
Object mc = (Object) list.get(4);
System.out.println("this is what i am --> " + mc.getClass().getCanonicalName());
output: "this is what i am --> MyClass"
thanks.
Message was edited by:
supponthe MyClass objects are not
initially loaded in the receiver's JVM.Make a custom class as:
public class CustomObjectInputStream extends ObjectInputStream {
private ClassLoader classLoader;
/** Creates a new instance of CustomObjectInputStream */
public CustomObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException {
super(in);
this.classLoader = classLoader;
protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
return Class.forName(desc.getName(), false, classLoader);
}and use an instance of this class instead of the standard object inputstream to deserialize your object. You should pass the url class loader as an argument to the constructor of the custom object input stream. The reason is that the standard object inputstream only recognises classes that are "statically defined in the JAVA class path". (I quote the last text because I am not sure if I am using the right terminology, but I hope you understand what I mean.)
why do i get
"ClassCastExceptions" ??
and not
"ClassNotFoundException"
??This must be because somehow you have a "static" class definition for MyClass anyway, otherwise you wouldn't be able to write the following code and have it compile:
MyClass item = (MyClass) class1.cast(list.get(7));Apparently your "static" MyClass definition does not correspond with the MyClass definition in your .jar file.
You can only access a deserialized object of which the class definition is in a .jar file through reflection, unless you can cast it to an interface with a "static" definition. -
Build XML for Custom Nested Accordian (like Tree View Structure) for SharePoint List Data
Expected output in Xml:
<?xml version="1.0" encoding="utf-8" ?>
- <TopRoot>
- <Root id="1" Name="Department">
- <Type id="2" Name="IT">
- <SubType id="3" Name="Technology">
<SubSubType id="4" Name="Sharepoint" />
<SubSubType id="5" Name="ASP.NET" />
<SubSubType id="6" Name="HTML 5" />
</SubType>
</Type>
</Root>
</TopRoot>
List Details:
list details for storing category / sub category data and code to build tree structure for the same.
1.Create Custom List named “CategoryDetails”:
2.Create Column “Category Name” of type single line of text. Make it as required field and check Yes for Enforce Unique values.
3.Create column “Parent Category” of type lookup. under Additional Column Settings.
Get information dropdown, select “CategoryDetails”.
4.Choice column ["SRTypeName"] 1.Root,2.SRTYPE,3.SubSRTYPE, 4.SUBSUBSRTYPE
In this column dropdown, select “Category Name”:
Referance:
http://www.codeproject.com/Tips/627580/Build-Tree-View-Structure-for-SharePoint-List-Data -fine but don't want tree view just generate xml string
i just follwed above link it work perferfectly fine for building tree view but i don't want server control.
Expected Result:
My ultimate goal is to generate xml string like above format without building tree view.
I want to generate xml using web service and using xml i could convert into nested Tree View Accordian in html.
I developed some code but its not working to generate xml /string.
My modified Code:
public const string DYNAMIC_CAML_QUERY =
"<Where><IsNull><FieldRef Name='{0}' /></IsNull></Where>";
public const string DYNAMIC_CAML_QUERY_GET_CHILD_NODE =
"<Where><Eq><FieldRef Name='{0}' /><Value Type='LookupMulti'>{1}</Value></Eq></Where>";
protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
string TreeViewStr= BuildTree();
Literal1.Text = TreeViewStr;
StringBuilder sbRoot= new StringBuilder();
protected string BuildTree()
SPList TasksList;
SPQuery objSPQuery;
StringBuilder Query = new StringBuilder();
SPListItemCollection objItems;
string DisplayColumn = string.Empty;
string Title = string.Empty;
string[] valueArray = null;
try
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
using (SPWeb web = site.OpenWeb())
TasksList = SPContext.Current.Web.Lists["Service"];
if (TasksList != null)
objSPQuery = new SPQuery();
Query.Append(String.Format(DYNAMIC_CAML_QUERY, "Parent_x0020_Service_x0020_Id"));
objSPQuery.Query = Query.ToString();
objItems = TasksList.GetItems(objSPQuery);
if (objItems != null && objItems.Count > 0)
foreach (SPListItem objItem in objItems)
DisplayColumn = Convert.ToString(objItem["Title"]);
Title = Convert.ToString(objItem["Title"]);
int rootId=objItem["ID"].ToString();
sbRoot.Append("<Root id="+rootId+"
Name="+Title+">");
string SRAndSUBSRTpe = CreateTree(Title, valueArray,
null, DisplayColumn, objItem["ID"].ToString());
sbRoot.Append(SRAndSUBSRTpe);
SRType.Clear();//make SRType Empty
strhtml.Clear();
SRType.Append("</Root>");
catch (Exception ex)
throw ex;
return SRType.ToString();
StringBuilder strhtml = new StringBuilder();
private string CreateTree(string RootNode, string[] valueArray,
List<SPListItem> objNodeCollection, string DisplayValue, string KeyValue)
try
strhtml.Appends(GetSRType(KeyValue, valueArray, objNodeCollection);
catch (Exception ex)
throw ex;
return strhtml;
StringBuilder SRType = new StringBuilder();
private string GetSRType(string RootNode,
string[] valueArray, List<SPListItem> objListItemColn)
SPQuery objSPQuery;
SPListItemCollection objItems = null;
List<SPListItem> objNodeListItems = new List<SPListItem>();
objSPQuery = new SPQuery();
string objNodeTitle = string.Empty;
string objLookupColumn = string.Empty;
StringBuilder Query = new StringBuilder();
SPList objTaskList;
SPField spField;
string objKeyColumn;
string SrTypeCategory;
try
objTaskList = SPContext.Current.Web.Lists["Service"];
objLookupColumn = "Parent_x0020_Service_x0020_Id";//objTreeViewControlField.ParentLookup;
Query.Append(String.Format
(DYNAMIC_CAML_QUERY_GET_CHILD_NODE, objLookupColumn, RootNode));
objSPQuery.Query = Query.ToString();
objItems = objTaskList.GetItems(objSPQuery);
foreach (SPListItem objItem in objItems)
objNodeListItems.Add(objItem);
if (objNodeListItems != null && objNodeListItems.Count > 0)
foreach (SPListItem objItem in objNodeListItems)
RootNode = Convert.ToString(objItem["Title"]);
objKeyColumn = Convert.ToString(objItem["ID"]);
objNodeTitle = Convert.ToString(objItem["Title"]);
SrTypeCategory= Convert.ToString(objItem["SRTypeName"]);
if(SrTypeCategory =="SRtYpe")
SRType.Append("<Type id="+objKeyColumn+" Name="+RootNode+ ">");
if (!String.IsNullOrEmpty(objNodeTitle))
SRType.Append(GetSRType(objKeyColumn, valueArray, objListItemColn));
if(SrTypeCategory =="SRSubTYpe")
SRType.Append("<SRSubType id="+objKeyColumn+" Name="+RootNode+
">");
if (!String.IsNullOrEmpty(objNodeTitle))
SRType.Append(GetSRType(objKeyColumn, valueArray, objListItemColn));
if(SrTypeCategory =="SubSubTYpe")
SRType.Append("<SubSubType id="+objKeyColumn+" Name="+RootNode +"
></SubSubType");
SRType.Append("</SubType>");
SRType.Append("</Type>");
catch (Exception ex)
throw ex;
return SRType.ToString();
// Call method again (recursion) to get the child itemsHi,
According to your post, my understanding is that you want to custom action for context menu in "Site Content and Structure" in SharePoint 2010.
In "SiteManager.aspx", SharePoint use MenuItemTemplate class which represent a control that creates an item in a drop-down menu.
For example, to create or delete the ECB menu for a list item in
"Site Content and Structure", we can follow the steps below:
To add the “My Like” menu, we can add the code below:
<SharePoint:MenuItemTemplate
UseShortId=false
id="OLListItemLike"
runat="server"
Text="My Like"
ImageUrl="/_layouts/images/DelItem.gif"
ClientOnClickNavigateUrl="https://www.google.com.hk/"
/>
To remove the “Delete” menu, we can comment the code below:
<SharePoint:MenuItemTemplate
UseShortId=false
id="OLListItemDelete"
runat="server"
Text="<%$Resources:cms,SmtDelete%>"
ImageUrl="/_layouts/images/DelItem.gif"
ClientOnClickScript="%SmtObjectDeleteScript%"
/>
The result is as below:
More information:
MenuItemTemplate Class (Microsoft.SharePoint.WebControls)
MenuItemTemplate.ClientOnClickScript property (Microsoft.SharePoint.WebControls)
Best Regards,
Linda Li
Linda Li
TechNet Community Support -
Revision: 11030
Author: [email protected]
Date: 2009-10-20 11:35:02 -0700 (Tue, 20 Oct 2009)
Log Message:
Tweak the deserialization of ASObjects to treat an empty string for the type of an object as null. It appears that there is some logic in the LC remoting code that relies on a non-null class name to always exist. This change reverts to the old behavior of not allowing empty string as a value for the ASObject.namedType.
This should fix bug 2448442 and its duplicates caused by the recent serialization changes.
I don't think this is the perfect fix. Pending further investigation, a better fix would be either:
a. If it's OK to assume that empty string should always mean null for the type of the ASObject, the code that enforces it should be in the setter/getter inside ASObject and not in the deserializer.
b. ASObject doesn't guarantee that a named type exists or is valid. In that sense an empty string is as bad as some random characters that cannot be a valid class name in java, so depending on how disruptive it may be, the fix should be in any logic that uses ASObject.getType().
Modified Paths:
blazeds/trunk/modules/core/src/flex/messaging/io/amf/AbstractAmfInput.javaHi Pavan,
"In your payload there is no namespace prefix for the elements under PayloadHeader element."
Yes, you are right - but this message is standard AQ Adapter Header message - it's not defined by me. I just used message which was automatically added to my project when I have defined AQ Adapter.
"In your process is the default namespace is same as namespace value of tns ??"
Do you mean targetNamespace? If yes it's different as it points to process "targetNamespace="http://xmlns.oracle.com/PF_SOA_jws/PF_APPS/APPS_PROCESS" (names of application and process have changed as I try different ways to do that)
ns1 is: xmlns:ns1="http://xmlns.oracle.com/pcbpel/adapter/aq/PF_SOA/PF_APPS/PO_AQ"
"another thing is tns and ns1 should have same values.."
When I create a variable of header type, namespace ns1 is automatically created for it. I set it as property of receive activity. When process is instantiated on the serwer I get the error in which you can see that namespace is tns.
Maybe I'm doing something wrong but I don't see how I could fix this in my process.
You can see that the message I get on the server has nothing in common with the application/project/process names. Is it possible to define such variable?
Regards
Pawel
PS:
In Transformation xsl file, both variables (source and target) has tns namespace for Header and PayloadHeader, and no namespace for subfields.
Edited by: pawel.fidelus on 2010-01-05 02:37 -
Hello friends,
We have created a archiving object in transaction AOBJ. However when i enter this object in SARA, we get this error message.
"Entry missing in Customizing table for object Z******* "
I have matched my object with few other archiving objects and things looks similar.
Have you faced this kind of problem..
thanks
ashishHi,
I checked and i can see entry for ZSCS_TRAFO object in AOBJ.
But when i enter ZSCS_TRAFO, i get this error :
Entry missing in Customizing table for object ZSCS_TRAFO
Message no. BA057
Diagnosis
A function cannot be executed due to a missing table entry.
Procedure
Please create an entry for the archive object ZSCS_TRAFO with the AOBJ transaction.
However, a few other Z objects works well.
thanks
ashish -
How to Enable Ratings on SharePoint List using Client Object Model code for Office 365 SharePoint Site.
Thanks in Advance
Rajendra KHi Rajendra,
here you are the code and the blog, let me know if this helps
using (ClientContext ctx = new ClientContext(https://yourSiteUrl))
Web w = ctx.Web;
List l = w.Lists.GetByTitle("yourListName");
ctx.Load(l, info => info.Id);
ctx.ExecuteQuery();
string ListID = l.Id.ToString();
Microsoft.Office.Server.ReputationModel.Reputation.SetRating(ctx, ListID, 1, 5);
ctx.ExecuteQuery();
http://blogs.technet.com/b/speschka/archive/2013/07/08/how-to-use-csom-with-ratings-in-sharepoint-2013.aspx
Kind Regards, John Naguib Technical Consultant/Architect MCITP, MCPD, MCTS, MCT, TOGAF 9 Foundation -
List of all objects authorized for standard abap role
Hi all,
Can any body help me to get " List of all objects authorized for standard abap role "
And List of all objects authorized for "admin role".
Thanks
BasuSee the database security guide http://docs.oracle.com/cd/B28359_01/network.111/b28531/authorization.htm#BABFHBFH
Finding Information About User Privileges and Roles
This section discusses the system views that have the grant information.
The tricky part of this is that because roles can be granted to other roles the data is hierarchical.
So start with the grants made to the FDIREADR role. So referring to the doc above;
select * from role_role_privs where role = 'FDIREADR'will list the roles granted to your role.
You will want to look at ROLE_ROLE_PRIVS, ROLE_TAB_PRIVS and ROLE_SYS_PRIVS.
I suggest you walk thru the views manually to see how the information is related. Then write a test script that queries the views for you. -
Hi All,
Any idea, which is the object type ( from NRIV table) for Task list gp.(transaction CA11)
Regards
SaurabhHi,
I think Number Range Object ROUTING_S "Number ranges for reference operation sets" is what you are looking for.
Regards,
James Gaddis -
Object type for Employee master for choose list
hi Experts
Can Any one tell me the object type for Employee master for choose list like for Bp master object type is 2 and 1 for Account master.
Thanks
GorgeHi Gorge,
You can find the full list in UI Help located in :
C:\Programm Files\SAP\SAP Business One SDK\Help\REFUI.chm (search for 'object type').
Employee is 171.
Bye -
Custom iterator for custom list. ClassNotFoundException()
I'm not sure what it is I'm doing wrong in this assignment We are to create a linked list with each node containing a fixed size array [8]
At the moment when running the speed test class (speed test tests arraylist, collection and the chunklist) my class is simply causing an infinite loop. (i think, nothing seems to be happening anyway)
when debugging if I try to step into certain things I get a ClassNotFoundException(); for example. the constructor for the list.
ChunkList()
if (head == null)
head = new Chunk<T> (head);
tail = new Chunk<T> (head);
}the line head = new Chunk<T>(head) causes this exception, however if I step over it in Eclipse it works fine, and seems to add data provided by the speed test. The same is happening with my iterator. When stepping over this however in the over-ridden Iterator it does not seem to be returning a ChunkItr
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ChunkList<T> extends AbstractCollection<T>
private final int ARRAY_SIZE = 8;
private Chunk<T> head;
private Chunk<T> tail;
private int numOfElements;
@SuppressWarnings("hiding")
private class Chunk<T>
public Object[] data = new Object[ARRAY_SIZE];
public Chunk<T> link;
public int chunkSize = 0;
@SuppressWarnings("unused")
public Chunk()
data = null;
link = null;
public Chunk(Chunk<T> link)
this.link = link;
public boolean equalsChunk(Chunk<T> c)
if (c == null)
return false;
else if (this.chunkSize != c.chunkSize)
return false;
else if (this.link != c.link)
return false;
else
Chunk<T> otherChunk = (Chunk<T>)c;
for(int i=0; i<ARRAY_SIZE; ++i)
if (!(this.data.equals(otherChunk.data[i])))
return false;
return true;
}// end of Chunk<T>
@SuppressWarnings("hiding")
private class ChunkItr<T> implements Iterator<T>
public Chunk<T> currentChunk;
public Chunk<T> previousChunk;
public Chunk<T> nextChunk;
public int currentElement;
@SuppressWarnings("unchecked")
public ChunkItr()
currentChunk = (Chunk<T>) head;
previousChunk = null;
nextChunk = (Chunk<T>) head;
currentElement = 0;
@Override
public boolean hasNext()
if (currentChunk != null)
if (currentElement < currentChunk.chunkSize)
return true;
return (nextChunk != null);
@SuppressWarnings("unchecked")
@Override
public T next()
if (!hasNext())
throw new NoSuchElementException();.
T elementToReturn = null;
while (elementToReturn == null)
if (currentChunk != null)
elementToReturn = (T) currentChunk.data[currentElement];
if ((currentElement == ARRAY_SIZE-1) ||
(currentElement == currentChunk.chunkSize))
previousChunk = currentChunk;
currentChunk = currentChunk.link;
currentElement = -1;
if (currentElement == 0)
nextChunk = nextChunk.link;
++currentElement;
else
break;
return elementToReturn;
@SuppressWarnings("unchecked")
@Override
public void remove()
if (currentChunk == null)
throw new IllegalStateException();
else if (currentChunk.data[currentElement] == null)
throw new IllegalStateException();
else
int move = currentChunk.chunkSize - currentElement;
for (int i=currentElement;i<move;++i)
currentChunk.data[i] = currentChunk.data[i+1];
// let gc do its work
currentChunk.data[currentChunk.chunkSize] = null;
--currentChunk.chunkSize;
--numOfElements;
} // did we just null first element?
if (currentChunk.chunkSize < 0)
if (currentChunk.equalsChunk((Chunk<T>) tail))
tail.link = tail;
//tail = (Chunk<T>) previousChunk;
} // re-link
currentChunk = currentChunk.link;
previousChunk.link = currentChunk;
} // end ChunkItr
public ChunkList()
head = null;
tail = null;
numOfElements = 0;
public void addNewChunk()
if (head == null)
head = new Chunk<T>(head);
tail = new Chunk<T>(head);
else
tail = new Chunk<T>(tail);
@Override
public boolean add(T t)
try
if (head == null)
addNewChunk();
tail.data[tail.chunkSize] = t;
++numOfElements;
if (tail.chunkSize == ARRAY_SIZE-1)
addNewChunk();
else
++tail.chunkSize;
return true;
catch(Exception e)
return false;
@Override
public Iterator<T> iterator()
return new ChunkItr<T>();
@Override
public int size()
return numOfElements;
public int numOfChunks()
int count=0;
Chunk<T> position = head;
while (position != null)
count++;
position = position.link;
return count;
// EOFI should ask this: What would be a better way to go about debugging this, besides the Eclipse debugger? because that just seems to give me runtime exceptions in places where it shouldn't.
speedtest
package chunklist;
//ChunkSpeed.java
This is a little class with a main() that runs some timing tests on
ArrayList, LinkedList, and ChunkList.
-- it's just static functions.
import java.util.*;
public class ChunkSpeed
// number of elements
public static final int MAX = 200000;
public static String FOO = "Foo";
Times a fixed series of add/next/remove calls
on the given collection. Returns the number
of milliseconds the operations took.
public static long test(Collection<String> coll)
long start = System.currentTimeMillis();
// Build the thing up
for (int i=0; i<MAX; i++)
coll.add(FOO);
// Iterate halfway through
Iterator<String>it = coll.iterator();
for (int i=0; i<MAX/2; i++)
it.next();
// Delete the next tenth
for (int i=0; i<MAX/10; i++)
it.next();
it.remove();
// Iterate over the whole thing (read-only) 5 times
int count = 0;
for (int i = 0; i<5; i++)
for (String s: coll)
if (s != null) count++;
long delta = System.currentTimeMillis() - start;
return(delta);
Runs the time test on the given collection and prints the result,
including the class name (cute use of getClass()).
public static void printTest(Collection<String> c)
long time = test(c);
System.out.printf("%s %d\n", c.getClass().toString(), time);
//////////////////////////////MAIN METHOD//////////////////////////////
public static void main(String[] args)
for (int i=0; i<5; i++)
printTest(new ArrayList<String>());
printTest(new LinkedList<String>());
printTest(new ChunkList<String>());
}//end main method
}//end class ChunkSpeedEdited by: Gcampton on Sep 2, 2010 8:57 PM -
Custom iterator for custom list.
I'm trying to write a custom iterator for custom linked list. What I don't understand is, whether the iterator should be in the link(node) inner-class or in the linked-list outer-class.
I seem to be getting errors in the outer-class, but in the inner-class it compiles fine. Whether or not it works is another story.
The code below is without errors in eclipse, however it doesn't make much sense to me to have the next() and hasNext() methods in the Node when the Iterator needs to iterate the list.
import java.util.*;
public class OctoList<T> extends AbstractCollection<T> implements Iterable<T>
// Inner Class
private class Octo<E>
// Octo will be a Node with 8 elements not including size, and links.
public Octo<T> next()
if (!hasNext())
throw new NoSuchElementException();
current = current.next();
return current;
public boolean hasNext()
return (current.next() != null);
// outer class
private Octo<T> head;
private Octo<T> tail;
private Octo<T> current = head;
private final int ARRAY_SIZE = 8;
@Override
public Iterator<T> iterator()
return null;
@Override
public int size()
return 0;
@Override
public boolean isEmpty()
return size() == 0;
}Gcampton wrote:
I'm trying to write a custom iterator for custom linked list. What I don't understand is, whether the iterator should be in the link(node) inner-class or in the linked-list outer-class.In the list class. After all, you're iterating a list, not a node.
I seem to be getting errors in the outer-class, but in the inner-class it compiles fine. Whether or not it works is another story.Then you'll have to fix those errors so it both compiles and works as intended.
You can create the iterator as an inner class in the list.
Maybe you are looking for
-
Issues with Cisco Prime LMS 4.2.3
Hi, I'm trailing Cisco Prime LMS 4.2.3 Soft appliance on ESXi before I deploy it into a live environment and am having some issues. I've upgraded to version 4.2.3 and the box was working fine after the upgrade however on power it up today the Apache
-
I have a Mac mini (bought in 2013) and the LG 20EN33 screen. I tried filing with the monitor's settings as well as the ones in display but the screen is stretched and the font is quite big. I saw a thread about Switch Res X so downloaded the app, but
-
Virus change language and I cannot sign in
Virus changed language setting in password so I cannot sign in
-
Why can't I back up my Macbook Air using Airport extreme.
I "used to" back up my Macbook air via Time machine using external harddisk connected to Airport extreme, of course back up wirelessly over WiFi. But now I've seen on Apple support page about Airport extreme that this cannot be done anymore. I've onl
-
Why won't Flash Player download?
I'm trying to download Flash Player on OS 10.6.8, but all that will download is the installer. When I click on he installer, it simply downloads the installer again. I've gone through all the suggestions on the Adobe site for this problem.